Collectors.groupingBy 用法记录

public class test {
public static void main(String[] args) throws ParseException {
// groupingBy
Map<String, List> tempMap = Stream.of(new Person("1", "aa", "12"), new Person("1", "bb", "13"), new Person("3", "cc", "14")).collect(Collectors.groupingBy(x -> x.id));

    for (String s : tempMap.keySet()) {
        System.out.println(s);
        tempMap.get(s).stream().forEach(x -> System.out.println(x));
    }

    Map<String, List<Person>> tempMap1 = Stream.of(new Person("1", "aa", "13"), new Person("1", "aa", "11"), new Person("1", "aa", "12"))
            .collect(Collectors.groupingBy(x -> fetchGroupKey(x)));
    System.out.println(tempMap1.keySet());
    for (String s : tempMap1.keySet()) {
        System.out.println(s);
        tempMap1.get(s).stream().forEach(x -> System.out.println(x));
    }

}

private static String fetchGroupKey(Person person){
    return person.getId()+"#"+person.getName()+"#"+person.getAge();
}

}

Map<String, List> tempMap:以person id作为分组的key,map中的key即为personid,list 即为id=map中key的集合。
Map<String, List> tempMap1:可以组合分组的key,map key 即为组合字段,list即为 组合key=map中key的集合。

以上代码输出:
1
Person{id='1', name='aa', age='12'}
Person{id='1', name='bb', age='13'}
3
Person{id='3', name='cc', age='14'}

[1#aa#12, 1#aa#13, 1#aa#11]
1#aa#12
Person{id='1', name='aa', age='12'}
1#aa#13
Person{id='1', name='aa', age='13'}
1#aa#11
Person{id='1', name='aa', age='11'}

posted @ 2021-03-10 08:52  于贰哥  阅读(4242)  评论(0编辑  收藏  举报