Java8中如何进行分组和缩减

正如我对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 **/

}


梵蒂冈之花
浏览 195回答 1
1回答

白衣染霜花

您可以使用 aCollectors.groupingBy(Subject::getSubject)和 aCollectors.mapping(Subject::getGrades, Collectors.toSet())作为下游。list.stream() &nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.groupingBy(Subject::getSubject, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Collectors.mapping(Subject::getGrades,&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Collectors.toSet())));它会给你一个Map<String, Set<Integer>>.{Lab=[10,&nbsp;12],&nbsp;Math=[1,&nbsp;2,&nbsp;3]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java