Java 从映射内的列表中删除重复的元素

Java 从映射内的列表中删除重复的元素,java,list,java-8,hashmap,Java,List,Java 8,Hashmap,假设我有以下地图: "A": [1, 2, 3, 4] "B": [5, 6, 1, 7] "C": [8, 1, 5, 9] 如何从数组中删除重复的元素以返回只包含从未重复的元素的映射 "A": [2, 3, 4] "B": [6, 7] "C": [8, 9] 首先,你必须计算每个列表中的数字 Map<Integer, Long> countMap = map.values().stream() .flatMap(List::stream)

假设我有以下地图:

"A": [1, 2, 3, 4]
"B": [5, 6, 1, 7]
"C": [8, 1, 5, 9]
如何从数组中删除重复的元素以返回只包含从未重复的元素的映射

"A": [2, 3, 4]
"B": [6, 7]
"C": [8, 9]

首先,你必须计算每个列表中的数字

Map<Integer, Long> countMap = map.values().stream()
            .flatMap(List::stream)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map countMap=Map.values().stream()
.flatMap(列表::流)
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting());
然后在count==1的位置进行筛选

Map<String, List<Integer>> result = map.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream()
                    .filter(i -> countMap.get(i) == 1).collect(Collectors.toList())));
Map result=Map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,e->e.getValue().stream())
.filter(i->countMap.get(i)=1.collect(Collectors.toList());

您可能希望这样做:

// Initializing the map
Map<String, List<Integer>> map = new LinkedHashMap<String, List<Integer>>() {
    {
        put("A", new ArrayList<>(Arrays.asList(1, 2, 3, 4)));
        put("B", new ArrayList<>(Arrays.asList(5, 6, 1, 7)));
        put("C", new ArrayList<>(Arrays.asList(8, 1, 5, 9)));
    }
};

// finding the common elements
List<Integer> allElements = map.values().stream().flatMap(List::stream).collect(Collectors.toList());
Set<Integer> allDistinctElements = new HashSet<>();
Set<Integer> commonElements = new HashSet<>();
allElements.forEach(element -> {
    if(!allDistinctElements.add(element)) {
        commonElements.add(element);
    }
});

// removing the common elements
map.forEach((key, list) -> list.removeAll(commonElements));

// printing the map
map.forEach((key, list) -> System.out.println(key + " = " + list));

请展示您所写的内容,以便更接近解决方案。迭代所有值,无论它们属于哪个键,计算每个值的数量(您可以使用Map)。现在你知道应该删除哪个字符了。这是家庭作业吗?不是家庭作业。我需要创建一个方法来接收如上所述的HashMap,我需要删除列表中重复出现的iten,但我无法解决这个问题。数字5也应该删除。@LucianoBorges Oops我以为您想删除所有列表中常见的元素。现在我已经更新了代码。请检查。使用带有副作用的
forEach
是个坏主意-read@Adrian我认为这与访问
静态映射有关,该映射在多线程(并行)中使用时共享,如
parallelStream
。我认为我的代码中不会有这样的问题。@LucianoBorges这个解决方案稍微好一点,因为我只使用了一个额外的映射,我只进行了2次迭代。而映射中的数组是一个对象数组,这个标识函数应该工作吗?因为,就我而言,它不起作用。是否需要在对象上创建equals方法?@LucianoBorges如果该对象将成为map的键,那么是的,您需要equals&hashCode。或者,如果您的对象具有例如唯一id,您可以使用例如
o->o.getId()
A = [2, 3, 4]
B = [6, 7]
C = [8, 9]