Partitioning a Map in Java 8+

  • A+
Category:Languages

I have a Map<String, String> and a List<String>. I'd like to partition the Map based on the condition

foreach(map.key -> list.contains(map.key)) 

and produce two Map(s). What's the most elegant way to do so? I'm on Java 11, so you can throw everything you want in the answers.

What I came up to for now is:

map.entrySet()    .stream()    .collect(partitioningBy(e -> list.contains(o.getKey()))); 

but that gives a Map<Boolean, List<Entry<String, String>>>.

 


You can reduce each group using toMap (as a downstream collector):

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)                     )         ); 

And for this example, that produces {false={A=A, d=D}, true={b=B, c=C}}

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: