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 根据条件将列表拆分为子列表


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01