天天看點

java 8 stream list 對象 轉map

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));