Java – splits the list into sub lists according to the conditions of the stream API

I have a specific question There are some similar problems, but these problems are either Python or Java, or even if the problems sound similar, the requirements are different

I have a list of values

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

At the end of the day, I want to split the list according to their values I mean, if the value is greater than zero, it will remain in the original list, and the corresponding index in the negative list will be set to zero If the value is less than zero, it goes to the negative value list and the negative value in the original list is replaced with zero

The result list should look like this;

List1 = {10,0}
List2 = {0,-99}

Is there any way to solve this problem with the stream API in Java?

Solution

If you want to perform this operation in a single stream operation, you need a custom collector:

List<Integer> list = Arrays.asList(10,-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));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>