使用 Stream api 根据条件将列表拆分为子列表
我有一个具体的问题.有一些类似的问题,但这些问题要么是 Python 的,而不是 Java 的,或者即使问题听起来相似,要求也不同.
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.
我有一个值列表.
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}
有没有办法用 Java 中的 Stream api 解决这个问题?
Is there any way to solve this with Stream api in Java?
推荐答案
如果要在单个 Stream 操作中完成,则需要自定义收集器:
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));
相关文章