Stream流Collectors.toMap用法


package com.best.buc.verification.constant;
 
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
 
@Getter
@Setter
@AllArgsConstructor
public class Person {
    private Integer id;
    private String name;
 
    public static void main(String[] args) {
        List<Person> list = new ArrayList();
        list.add(new Person(1, "1"));
//        list.add(new Person(1, "4"));
        list.add(new Person(2, "2"));
        list.add(new Person(3, "3"));
 
        Map<Integer, Person> collect = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));
        Map<Integer, Person> collect1 = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (a,b)->a));
        Map<Integer, Person> collect2 = list.stream().collect(Collectors.toMap(Person::getId, v -> v, (a,b)->a));
        Collection<Person> values = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (a, b) -> a)).values();
        long count = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (a, b) -> a)).values().stream().count();
        System.out.println(collect);
        System.out.println(collect1);
        System.out.println(collect2);
        System.out.println(values);
        System.out.println(count);
    }
}

 

使用toMap()函數之后,返回的就是一個Map了,自然會需要key和value。
toMap()的第一個參數就是用來生成key值的,第二個參數就是用來生成value值的。
第三個參數用在key值沖突的情況下:如果新元素產生的key在Map中已經出現過了,第三個參數就會定義解決的辦法。

在.collect(Collectors.toMap(Person::getId, v -> v, (a,b)->a))中:

第一個參數:Person:getId表示選擇Person的getId作為map的key值;

第二個參數:v->v表示選擇將原來的對象作為Map的value值

第三個參數:(a,b)->a中,如果a與b的key值相同,選擇a作為那個key所對應的value值。

如果key沖突,不加(a,b)->a會報如下錯誤

 

 

————————————————
版權聲明:本文為CSDN博主「星夜孤帆」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_38826019/article/details/109401567


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM