java8 list转Map报错Collectors.toMap :: results in "Non-static method cannot be refernced from static context" java8--List转为Map、分组、过滤、求和等操作

1.问题:java8 list转Map

报错Collectors.toMap :: results in "Non-static method cannot be refernced from static context"

 解决:将第二个参数传入function

 原因:Collectors.toMap参数接收为function

2.解决key重复问题:

        Map<String,String> map2=list.stream().collect(Collectors.toMap(Person::getName,o->"",(key1,key2)->key2));

输出:{cc=, bb=, aa22=, aa11=}

3.value为对象本身,注意map泛型为Person

Person

public  class Person {
    private String id;
    private String name;

    public  String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Person(String name) {
        this.name = name;
    }

    public Person(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }

map

List<Person> list=new ArrayList<>();

list.add(new Person("aa","aa11"));
list.add(new Person("bb",""));
list.add(new Person("aa","aa22"));
list.add(new Person("cc",""));

Map<String,Person> map2=list.stream().collect(Collectors.toMap(o->o.getId(),o->o,(key1,key2)->key2));//重复时取后面的
//Map<String,Person> map2=list.stream().collect(Collectors.toMap(o->o.getId(), Function.identity(),(key1, key2)->key2));//优雅写法
System.out.println(map2);

输出:{cc=Person{id='cc', name=''}, bb=Person{id='bb', name=''}, aa=Person{id='aa', name='aa22'}}

 4.排序:

        Map<String,String> map2=list.stream().collect(Collectors.toMap(Person::getId,Person::getName ,(key1, key2)->key2,TreeMap<String,String>::new));

输出{aa=aa22, bb=, cc=}

其它:java8--List转为Map、分组、过滤、求和等操作 

猜你喜欢

转载自www.cnblogs.com/pu20065226/p/11456988.html