List转Map
1、传统方法
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) { Map<Integer, Animal> map = new HashMap<>(); for (Animal animal : list) { map.put(animal.getId(), animal); } return map; }
2、stream
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) { Map<Integer, Animal> map = list.stream() .collect(Collectors.toMap(Animal::getId, Function.identity())); return map; }
3、Guava库
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
Map<Integer, Animal> map = Maps
.uniqueIndex(list, Animal::getId);
return map;
}
4、Apache Commons库
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
public Map<Integer, Animal> convertListWithApacheCommons2(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
key冲突情况
Apache Commons 和 Java 8 之前的代码是一样的,相同id的Map 在put 的时候会进行覆盖。
而 Java 8 的 Collectors.toMap() 和 Guava 的 MapUtils.populateMap() 分别抛出 IllegalStateException 和 IllegalArgumentException。

浙公网安备 33010602011771号