1. Problem: java8 list turn Map
报错Collectors.toMap :: results in "Non-static method cannot be refernced from static context"
Solution: The second argument to function
The reason: Collectors.toMap received as a function parameter
2. Repeat solve key problems:
Map<String,String> map2=list.stream().collect(Collectors.toMap(Person::getName,o->"",(key1,key2)->key2));
Output: {cc =, bb =, aa22 =, aa11 =}
3.value as the object itself, note that the generic map to 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. Sort by:
Map<String,String> map2=list.stream().collect(Collectors.toMap(Person::getId,Person::getName ,(key1, key2)->key2,TreeMap<String,String>::new));
Output {aa = aa22, bb =, cc =}
Other: java8 - List into the Map, packet filtering, and summation operations