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、分组、过滤、求和等操作 

posted on 2019-09-04 09:20  pu20065226  阅读(1479)  评论(0编辑  收藏  举报