开发过程中我们会遇到List<Entity>转Map<String,Entity>的场景,但是如果出现重复的key会报 Duplicate key异常。
代码如下有附件:
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ListToMapDuplicateKey {
public static void main(String[] args) {
List<Goods> list = new ArrayList<>();
Goods goods1 = new Goods();
goods1.setGoodsCode("mer1");
goods1.setGoodsName("苹果");
list.add(goods1);
Goods goods2 = new Goods();
goods2.setGoodsCode("mer2");
goods2.setGoodsName("梨");
list.add(goods2);
Goods goods3 = new Goods();
goods3.setGoodsCode("mer2");
goods3.setGoodsName("梨2");
list.add(goods3);
//IllegalStateException Duplicate key
// Map<String,Goods> goodsMap=list.stream().collect(Collectors.toMap(Goods::getGoodsCode,goods ->{return goods ;}));
//解决办法 如果出现重复的key,(v1,v2)->v1) 优先取第一个 (v1,v2)->v2) 优先取最后一个
Map<String, Goods> goodsMap = list.stream().collect(Collectors.toMap(Goods::getGoodsCode, Function.identity(), (v1, v2) -> v1));
System.out.println(goodsMap);
}
}
class Goods {
//商品编码
private String goodsCode;
//商品名称
private String goodsName;
public String getGoodsCode() {
return goodsCode;
}
public void setGoodsCode(String goodsCode) {
this.goodsCode = goodsCode;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
@Override
public String toString() {
return "Goods{" +
"goodsCode='" + goodsCode + '\'' +
", goodsName='" + goodsName + '\'' +
'}';
}
}