根据Stream api的条件将列表拆分为子列表 [英] Split a list into sublists based on a condition with Stream api

查看:64
本文介绍了根据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.

结果列表应为那样;

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的条件将列表拆分为子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆