为了账号安全,请及时绑定邮箱和手机立即绑定

Java8中如何进行分组和缩减

Java8中如何进行分组和缩减

梵蒂冈之花 2023-06-28 15:37:55
正如我对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 **/}
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

您可以使用 aCollectors.groupingBy(Subject::getSubject)和 aCollectors.mapping(Subject::getGrades, Collectors.toSet())作为下游。

list.stream()
    .collect(Collectors.groupingBy(Subject::getSubject,
                 Collectors.mapping(Subject::getGrades, 
                     Collectors.toSet())));

它会给你一个Map<String, Set<Integer>>.

{Lab=[10, 12], Math=[1, 2, 3]}


查看完整回答
反对 回复 2023-06-28
  • 1 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信