有一个question的list,question中有questionId和一个pointIdList,pointIdList中都是字符串格式的pointId,请使用java代码将listzhuanc已pointId为key值,已questionid的集合为value的map
时间: 2024-05-09 19:14:45 浏览: 114
好的,下面是Java代码实现:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Question> questionList = new ArrayList<>();
// 添加数据
List<String> pointIdList1 = new ArrayList<>();
pointIdList1.add("pointId1");
pointIdList1.add("pointId2");
Question question1 = new Question("questionId1", pointIdList1);
questionList.add(question1);
List<String> pointIdList2 = new ArrayList<>();
pointIdList2.add("pointId3");
pointIdList2.add("pointId4");
Question question2 = new Question("questionId2", pointIdList2);
questionList.add(question2);
// 转换为Map
Map<String, List<String>> map = new HashMap<>();
for (Question question : questionList) {
map.put(question.getQuestionId(), question.getPointIdList());
}
System.out.println(map); // 输出结果:{questionId1=[pointId1, pointId2], questionId2=[pointId3, pointId4]}
}
}
class Question {
private String questionId;
private List<String> pointIdList;
public Question(String questionId, List<String> pointIdList) {
this.questionId = questionId;
this.pointIdList = pointIdList;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public List<String> getPointIdList() {
return pointIdList;
}
public void setPointIdList(List<String> pointIdList) {
this.pointIdList = pointIdList;
}
}
```
首先定义了一个Question类,包含了questionId和pointIdList两个属性。然后定义了一个questionList列表,包含了若干个Question对象。最后通过for循环,将questionList转换为一个Map对象,其中key值为questionId,value为pointIdList。最终输出了转换后的Map对象。
阅读全文