Split a list into sublists based on a condition with Stream api

Viewed 40237

I have a specific question. There are some similar questions but these are either with Python, not with Java, or the requirements are different even if the question sounds similar.

I have a list of values.

List1 = {10, -2, 23, 5, -11, 287, 5, -99}

At the end of the day, I would like to split lists based on their values. I mean if the value is bigger than zero, it will be stay in the original list and the corresponding index in the negative values list will be set zero. If the value is smaller than zero, it will go to the negative values list and the negative values in the original list will be replaced with zero.

The resulting lists should be like that;

List1 = {10, 0, 23, 5, 0, 287, 5, 0}
List2 = {0, -2, 0, 0, -11, 0, 0, -99}

Is there any way to solve this with Stream api in Java?

8 Answers
Map<Boolean, List<Integer>> results=
  List1.stream().collect(Collectors.partitioningBy( n -> n < 0));

I think that this one is prettier and easy to read. (You can then get the negative and non-negative list from the map.)

Since Java 12 it can be done very simple by using Collectors::teeing:

var divided = List.of(10, -2, 23, 5, -11, 287, 5, -99)
            .stream()
            .collect(Collectors.teeing(
                    Collectors.mapping(i -> Math.max(0, i), Collectors.toList()),
                    Collectors.mapping(i -> Math.min(0, i), Collectors.toList()),
                    List::of
            ));

There are pros and cons in each solution.

  • for loop is the obvious answer, but your question explicitly mentions Streams API.
  • Using different predicates a) causes code duplication, b) is error prone, c) results in additional processing time — 2N
  • Custom Collector is difficult to implement, and gives the impression of redundant work while the problem seems so straightforward, even naïve.

I haven't seen anyone else mentioning this, but you can collect your numbers in a Map<Boolean,List<Integer>> map, where key corresponds to your grouping criterion, and List is the selection of items matching the criterion, for example:

List<Integer> numbers = List.of(10, -2, 23, 5, -11, 287, 5, -99);
Map<Boolean, List<Integer>> numbersByIsPositive = numbers.stream()
    .collect(Collectors.groupingBy(number -> number >= 0));

List<Integer> positiveNumbers = numbersByIsPositive.get(true);
List<Integer> negativeNumbers = numbersByIsPositive.get(false);

Think of auto-boxing and -unboxing when applying this approach.

Output:

Positive numbers: [10, 23, 5, 287, 5]
Negative numbers: [-2, -11, -99]
Related