List<Person> list = new ArrayList<>();
1.對象中的屬性轉map 通過Collectors.toMap
list.stream().collect(Collectors.toMap(Person::getId,Person::getName));
2.收集對象本身
list.stream().collect(Collectors.toMap(Person::getId,list->list));
list->list 是一個返回本身的lambda表達式,還可以用function接口中的一個默認方法Function.identity(),返回對象本身
list.stream().collect(Collectors.toMap(Person::getId,Function.identity()));
3.key重復的情況,key有可能重復,會跑出異常:java.lang.illegalStateException:Duplicate key.這時候就要在toMap
方法指定當前key沖突時key的選擇,這里時第二個key覆蓋第一個key
list.stream().collect(Collectors.toMap(Person::getName,Function.identity(),(key1,key2)->key2));
4.根據一個字段或者屬性分組也可以直接用groupingby方法
list.list(100).collect(Collectors.groupingBy(Person::getAge));
通過partitioningBy 進行分組
list.limit(100).collect(Collectors.partitioningBy(p-P.getAge()<18));