SHARE
TWEET

stream api: partition by

DulcetAirman Feb 5th, 2018 32 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin;
  2.  
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Map.Entry;
  7. import java.util.stream.Collectors;
  8.  
  9. public class SomeClass {
  10.     public static void main(String[] args) {
  11.         HashMap<Integer, String> map = new HashMap<>();
  12.         map.put(1, "foo");
  13.         map.put(2, "bar");
  14.         map.put(3, "qux");
  15.         map.put(4, "grault");
  16.         map.put(5, "garply");
  17.         map.put(6, "thud");
  18.         map.put(7, "flob");
  19.         System.out.println(map);
  20.         // {1=foo, 2=bar, 3=qux, 4=grault, 5=garply, 6=thud, 7=flob}
  21.  
  22.         Map<Boolean, Map<Integer, String>> part = map.entrySet().stream().collect(//
  23.                 Collectors.partitioningBy(e -> e.getValue().contains("a"),
  24.                         Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
  25.  
  26.         Map<Integer, String> containsA = part.get(true);
  27.         Map<Integer, String> rest = part.get(false);
  28.  
  29.         System.out.println(containsA); // {2=bar, 4=grault, 5=garply}
  30.         System.out.println(rest); // {1=foo, 3=qux, 6=thud, 7=flob}
  31.     }
  32. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top