猿问

从地图内的列表中删除重复的元素

假设我有以下地图:


"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]


慕村225694
浏览 131回答 2
2回答

白衣染霜花

您可能想这样做:// Initializing the mapMap<String, List<Integer>> map = new LinkedHashMap<String, List<Integer>>() {&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; put("A", new ArrayList<>(Arrays.asList(1, 2, 3, 4)));&nbsp; &nbsp; &nbsp; &nbsp; put("B", new ArrayList<>(Arrays.asList(5, 6, 1, 7)));&nbsp; &nbsp; &nbsp; &nbsp; put("C", new ArrayList<>(Arrays.asList(8, 1, 5, 9)));&nbsp; &nbsp; }};// finding the common elementsList<Integer> allElements = map.values().stream().flatMap(List::stream).collect(Collectors.toList());Set<Integer> allDistinctElements = new HashSet<>();Set<Integer> commonElements = new HashSet<>();allElements.forEach(element -> {&nbsp; &nbsp; if(!allDistinctElements.add(element)) {&nbsp; &nbsp; &nbsp; &nbsp; commonElements.add(element);&nbsp; &nbsp; }});// removing the common elementsmap.forEach((key, list) -> list.removeAll(commonElements));// printing the mapmap.forEach((key, list) -> System.out.println(key + " = " + list));输出:A = [2, 3, 4]B = [6, 7]C = [8, 9]

繁花如伊

首先你必须计算每个列表中的数字Map<Integer,&nbsp;Long>&nbsp;countMap&nbsp;=&nbsp;map.values().stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.flatMap(List::stream) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.groupingBy(Function.identity(),&nbsp;Collectors.counting()));然后过滤其中 count == 1Map<String,&nbsp;List<Integer>>&nbsp;result&nbsp;=&nbsp;map.entrySet().stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toMap(Map.Entry::getKey,&nbsp;e&nbsp;->&nbsp;e.getValue().stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(i&nbsp;->&nbsp;countMap.get(i)&nbsp;==&nbsp;1).collect(Collectors.toList())));
随时随地看视频慕课网APP

相关分类

Java
我要回答