首页 > 其他分享 >Stream流Collectors.toMap用法

Stream流Collectors.toMap用法

时间:2022-11-25 16:12:54浏览次数:36  
标签:toMap Collectors Stream collect list Person import


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所对应的v

如果key冲突,不加(a,b)->a会报如下错误


标签:toMap,Collectors,Stream,collect,list,Person,import
From: https://www.cnblogs.com/fuqian/p/16925481.html

相关文章