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