java 8 stream list 转 map(toMap) Duplicate key 异常重现与解决

@Test
public void duplicateKeyDemo(){
    // 测试数据
    List list = this.getCommodityList();

    // 去重
    Map mapSuccess = list.stream()
            .collect(Collectors.toMap(Commodity::getCode,  Function.identity(),(commodity1, commodity2) -> commodity1));

    log.info("mapSuccess:{}", mapSuccess);

    // 异常
    Map mapError = list.stream()
            .collect(Collectors.toMap(Commodity::getCode, (p) -> p));

    log.info("mapError:{}", mapError);
}

private List getCommodityList(){
    List list = new ArrayList<>();
    list.add(new Commodity("apple8", 8888));
    list.add(new Commodity("apple8", 9999));
    list.add(new Commodity("huawei", 6666));
    list.add(new Commodity("xiaomi", 5555));
    return list;
}

你可能感兴趣的:(java 8 stream list 转 map(toMap) Duplicate key 异常重现与解决)