Java 通过List<String>对Map<String, String>中key和value分区分组的方法及示例代码

本文主要介绍Java中,通过foreach(map.key -> list.contains(map.key))条件,对Map<String, String>p中key在List<String>中和不在的进行分区的方法,及相关示例代码。

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 的几种方法

Java 将List String 转换成 Map String,List String 的几种方法

Java Stream Collectors.groupingBy实现对List(列表)进行分组的方法

推荐阅读
cjavapy编程之路首页