fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.function.Predicate;
  10. import java.util.stream.Collectors;
  11.  
  12. /* Name of the class has to be "Main" only if the class is public. */
  13. class Ideone
  14. {
  15. public static void main (String[] args) throws java.lang.Exception
  16. {
  17. //My silly test predicate
  18. Predicate<String> p = s -> s.length() > 4;
  19.  
  20. //List with test strings (even though it's called numbers...)
  21. List<String> numbers = new ArrayList<>(List.of("Ted", "James", "Bobby", "Mark", "Hank", "Richard"));
  22.  
  23. //Partitioning by your first example
  24. Map<Boolean, List<String>> partitioned = numbers.stream()
  25. .collect(Collectors.partitioningBy(p));
  26.  
  27. //Printing the result
  28. System.out.println(partitioned);
  29.  
  30. //Partitioning with int keys
  31. Map<Integer, List<String>> partitioned2 = numbers.stream()
  32. .collect(Collectors.toMap(s -> p.test(s) ? 1 : 0, s -> new ArrayList<>(List.of(s)), (list1, list2) -> {
  33. list1.addAll(list2);
  34. return list1;
  35. }));
  36.  
  37. //Printing the second partition to compare it with the first one
  38. System.out.println(partitioned2);
  39. }
  40. }
Success #stdin #stdout 0.12s 52448KB
stdin
Standard input is empty
stdout
{false=[Ted, Mark, Hank], true=[James, Bobby, Richard]}
{0=[Ted, Mark, Hank], 1=[James, Bobby, Richard]}