2 回答
TA贡献1796条经验 获得超10个赞
您可能想这样做:
// 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]
TA贡献2012条经验 获得超12个赞
首先你必须计算每个列表中的数字
Map<Integer, Long> countMap = map.values().stream() .flatMap(List::stream) .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())));
添加回答
举报