Learnitweb

Partition a List into Even and Odd Numbers

Approach 1: Using Collectors.partitioningBy()

List<Integer> nums3 = Arrays.asList(1,2,3,4,5,6);
Map<Boolean, List<Integer>> parts = nums3.stream()
                                         .collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(parts); // {false=[1,3,5], true=[2,4,6]}

Why it works:

  • partitioningBy creates two buckets: true and false.

Approach 2: Using Collectors.toCollection (Alternative)

Map<Boolean, Set<Integer>> parts = nums3.stream()
                                        .collect(Collectors.partitioningBy(n -> n % 2 == 0, Collectors.toCollection(LinkedHashSet::new)));
System.out.println(parts);

Why it works:

  • Control collection type for uniqueness and order.