Split a list into sublists based on a condition with Stream api(使用 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));
这篇关于使用 Stream api 根据条件将列表拆分为子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Stream api 根据条件将列表拆分为子列表
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
