假设我有以下地图:
"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]
分析解答
你可能想这样做:
// 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));
输出:
A = [2, 3, 4]
B = [6, 7]
C = [8, 9]