Search code examples
javajava-stream

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


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?


Solution

  • If you want to do it in a single Stream operation, you need a custom collector:

    List<Integer> list = Arrays.asList(10, -2, 23, 5, -11, 287, 5, -99);
    
    List<List<Integer>> result = list.stream().collect(
        () -> Arrays.asList(new ArrayList<>(), new ArrayList<>()),
        (l,i) -> { l.get(0).add(Math.max(0, i)); l.get(1).add(Math.min(0, i)); },
        (a,b) -> { a.get(0).addAll(b.get(0)); a.get(1).addAll(b.get(1)); });
    
    System.out.println(result.get(0));
    System.out.println(result.get(1));