3

I have recently faced an interview question where I was required to filter out odd and even numbers from a List. The only catch was that I could not use 2 filters like the following:

List<Integer> nums = Arrays.asList(1,2,3,4,5);
        
List<Integer> odd = nums.stream().filter(n -> n%2 != 0).collect(Collectors.toList());
        
List<Integer> even = nums.stream().filter(n -> n%2 == 0).collect(Collectors.toList());

I said it was not possible since the final collect method can only return 1 single list.

What am I missing?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ng.newbie
  • 2,807
  • 3
  • 23
  • 57

1 Answers1

9

You can use Collectors.partitioningBy:

Map<Boolean, List<Integer>> response = nums.stream()
        .collect(Collectors.partitioningBy(n -> n % 2 == 0));

This will return :

{false=[1, 3, 5], true=[2, 4]}

to separate them you can use:

List<Integer> evens = response.get(true);
List<Integer> odds = response.get(false);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • GM Sir. Time for another Q review? https://stackoverflow.com/questions/66329361/how-to-avoid-code-duplication-in-gradle-configuration-code ? – GhostCat Feb 23 '21 at 08:20