1、使用partitioningBy和toMap实现
Map<String, String> myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List<String> myList = Arrays.asList("a", "b", "c");
Map<Boolean, Map<String, String>> 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<String, String> myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List<String> list = Arrays.asList("a", "b", "c");
Map<Boolean, Map<String, String>> result = Map.of(true, new LinkedHashMap<>(),
false, new LinkedHashMap<>());
Set<String> 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<String, String> myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List<String> list = Arrays.asList("a", "b", "c");
Map<String, String> contains = new HashMap<>();
Map<String, String> containsNot = new HashMap<>();
for(Map.Entry<String, String> 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<String, String> myMap = new HashMap<>();
myMap.put("d", "D");
myMap.put("c", "C");
myMap.put("b", "B");
myMap.put("A", "A");
List<String> myList = Arrays.asList("a", "b", "c");
Function<Entry<String, String> , Boolean> myCondition = i -> myList.contains(i.getKey());
Map<Boolean,List<Entry<String, String>>> myPartedMap = myMap.entrySet()
.stream().collect(Collectors.groupingBy(myCondition));
System.out.println(myPartedMap);
结果:
{false={A=A, d=D}, true={b=B, c=C}}
相关文档:
Java 使用stream()将Map String, List String 数据求和(sum)方法代码
Java 将List Object 转换成 Map String, Map String,List Object 的几种方法