list 转map java 8提供了很便捷的操作,有几个注意点需要注意下
若是存在key重复没有,采用相应的方式则会报错:Duplicate key 异常
下面简单记录下几种常用方式
以Person对象为例
@Data
@AllArgsConstructor
public class Person {
private int id;
private String name;
private int age;
}
1 直接使用唯一标志转map
List<Person> list = new ArrayList();
Person p1 = new Person(1, "one", 20);
list.add(p1);
p1 = new Person(2, "tom", 23);
list.add(p1);
p1 = new Person(3, "jetty", 24);
list.add(p1);
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));
或者只想提取某个字段
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));
这样也可以
Map<Integer, String> result3 = list.stream().collect(Collectors.toMap(p -> p.getId(), p -> p.getName()));
2 存在重复,后者覆盖前者
List<Person> list = new ArrayList();
Person p1 = new Person(1, "one", 20);
list.add(p1);
p1 = new Person(2, "tom", 23);
list.add(p1);
p1 = new Person(2, "jetty", 24);
list.add(p1);
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (key1, key2) -> key2));
3 合并成集合map 中存list 这种情况也是有的,例把年龄一样的,存在一起
Map<Integer, List<Person>> groupBy = appleList.stream().collect(Collectors.groupingBy(Person::getAge));
或
List<Person> list = new ArrayList();
Person p1 = new Person(1, "one", 24);
list.add(p1);
p1 = new Person(2, "tom", 23);
list.add(p1);
p1 = new Person(2, "jetty", 24);
list.add(p1);
Map<Integer, List<Person>> personMap = list.stream().collect(Collectors.toMap(Person::getAge,
p -> {
List<Person> personList = new ArrayList<>();
personList.add(p);
return personList;
},
(List<Person> l1, List<Person> l2) -> {
l1.addAll(l2);
return l1;
}
));
System.err.println(JSON.toJSONString(personMap));
ps 也可以指定map的实现类,满足些特殊要求,比如顺序
List<Person> list = new ArrayList();
Person p1 = new Person(1, "one", 20);
list.add(p1);
p1 = new Person(2, "tom", 23);
list.add(p1);
p1 = new Person(2, "jetty", 24);
list.add(p1);
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (key1, key2) -> key2,LinkedHashMap::new));
-- 根据某个字段分组并提取某个字段列表
Person p1 = new Person(1, "one", 20);
list.add(p1);
p1 = new Person(2, "tom", 23);
list.add(p1);
p1 = new Person(2, "jetty", 24);
list.add(p1);
p1 = new Person(3, "spring", 24);
list.add(p1);
Map<Integer, List<String>> group = list.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.mapping(Person::getName, Collectors.toList())));