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'}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM