java.lang.IllegalStateException: Duplicate key 0

错误信息

java.lang.IllegalStateException: Duplicate key 测试1
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1245)
	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
	at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)

测试代码

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Huathy
 * @ClassPath: PACKAGE_NAME.Test
 * @Date: 2021-03-13 17:34
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        List<Map.Entry> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map.Entry entry = new AbstractMap.SimpleEntry<>(1,i);
            list.add(entry);
        }
        Map<Object, Object> map = list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        System.out.println(map);
    }
}

解决方案

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Huathy
 * @ClassPath: PACKAGE_NAME.Test
 * @Date: 2021-03-13 17:34
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        List<Map.Entry> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map.Entry entry = new AbstractMap.SimpleEntry<>(1,i);
            list.add(entry);
        }
        Map<Object, Object> map = list.stream().collect(
                Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        //以最后一个元素为准,更新
                        //(e1,e2) -> e2
                        //以第一个元素为准,不更新
                        (e1,e2) -> e1
                ));
        System.out.println(map);
    }
}
上一篇:苹果Mac重复文件清理工具:Duplicate File Finder Pro


下一篇:Cisdem Duplicate Finder:快速查找和删除苹果Mac中重复文件