正如我对List主题的了解
"Subjects":[
{"subject":"Math","grades":1},
{"subject":"Math","grades":2},
{"subject":"Math","grades":3},
{"subject":"Math","grades":3},
{"subject":"Lab","grades":10},
{"subject":"Lab","grades":12}
]
我想像这样分组和减少结果
//Expected Result
"Subjects":[
{"subject":"Math","grades":[1,2,3]},
{"subject":"Lab","grades":[10,12]}
]
我很好奇如何以 java8 风格映射和减少对象。我在下面放置了过时的代码。
我的主课
public static void main(String[] args) {
List<Subject> list = new ArrayList<>();
list.add(new Subject("Math",1));
list.add(new Subject("Math",2));
list.add(new Subject("Math",3));
list.add(new Subject("Math",3));
list.add(new Subject("Lab",10));
list.add(new Subject("Lab",12));
Map<String, Set<Integer>> result = new HashMap<>();
list.stream().forEach(subjects-> {
if(result.get(subjects.getSubject())==null){
Set<Integer> set = new HashSet<>();
set.add(subjects.getGrades());
result.put(subjects.getSubject(),set );
}else{
Set<Integer> set =result.get(subjects.getSubject());
set.add(subjects.getGrades());
result.put(subjects.getSubject(), set);
}
});
result.forEach((key,val)->{
System.out.println("KEY:"+key + " RESULT :"+val);
});
}
public class Subject {
private String subject;
private Integer grades;
public Subject(String subject , Integer grade) {
this.subject = subject;
this.grades = grade;
}
/** get set **/
}
白衣染霜花
相关分类