1、使用partitioningBy和toMap实现Map myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List myList = Arrays.asList("a", "b", "c");
Map> result = myMap.entrySet()
.stream()
.collect(Collectors.partitioningBy(
entry -> myList.contains(entry.getKey()),
Collectors.toMap(Entry::getKey, Entry::getValue)
)
);
结果:{false={A=A, d=D}, true={b=B, c=C}}
2、使用forEach实现Map myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List list = Arrays.asList("a", "b", "c");
Map> result = Map.of(true, new LinkedHashMap<>(),
false, new LinkedHashMap<>());
Set set = new HashSet<>(list);
myMap.forEach((k, v) -> result.get(set.contains(k)).put(k, v));
结果:{false={A=A, d=D}, true={b=B, c=C}}
3、使用for实现Map myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List list = Arrays.asList("a", "b", "c");
Map contains = new HashMap<>();
Map containsNot = new HashMap<>();
for(Map.Entry entry : myMap.entrySet()) {
if (list.contains(entry.getKey())) {
contains.put(entry.getKey(), entry.getValue());
} else {
containsNot.put(entry.getKey(), entry.getValue());
}
}
结果:{false={A=A, d=D}, true={b=B, c=C}}
4、使用groupingBy实现Map myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List myList = Arrays.asList("a", "b", "c");
Function , Boolean> myCondition = i -> myList.contains(i.getKey());
Map>> myPartedMap = myMap.entrySet()
.stream().collect(Collectors.groupingBy(myCondition));
System.out.println(myPartedMap);
结果:{false={A=A, d=D}, true={b=B, c=C}}
相关文档: