如何使用Java 8流将条件与条件分开 [英] How to separate a List by a condition using Java 8 streams

查看:126
本文介绍了如何使用Java 8流将条件与条件分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

 List<Integer> odd = new ArrayList<Integer>();
 List<Integer> even = null;  
 List<Integer> myList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
 even = myList.stream()
              .filter(item -> {
                   if(item%2 == 0) { return true;}
                   else { 
                           odd.add(item); 
                           return false;
                   }
              })
              .collect(Collectors.toList());

我在这里要做的是将列表中的偶数和奇数值分别放入单独的列表中。

What I am trying to do here is get the even and odd values from a list into separate lists.

filter()方法返回 true for偶数项和流收集器将收集它们。

对于奇数情况,过滤器将返回 false ,该项目永远不会到达收集器。

The stream filter() method returns true for even items and the stream collector will collect them.
For the odd case, the filter will return false and the item will never reach the collector.

所以我在之前在 else 块下创建的另一个列表中添加了这些奇数。

So I am adding such odd numbers in another list I created before under the else block.

我知道这不是处理流的优雅方式。例如,如果我使用并行流,则奇数列表会出现线程安全问题。由于性能原因,我不能使用不同的过滤器多次运行它(应该是O(n))。

I know this is not an elegant way of working with streams. For example if I use a parallel stream then there will be thread safety issue with the odd list. I cannot run it multiple times with different filters because of performance reasons (should be O(n)).

这只是一个用例的例子,列表可以包含任何对象,并且过滤器内的lambda需要根据某些逻辑将它们分离到单独的列表中。

This is just an example for one use-case, the list could contain any object and the lambda inside the filter needs to separate them based on some logic into separate lists.

简单来说:从列表中创建多个包含基于某些条件分隔的项目的列表。

In simple terms: from a list create multiple lists containing items separated based on some criteria.

没有流,只需要运行for循环并执行简单的if-else并根据条件收集项目。

Without streams it would be just to run a for loop and do simple if-else and collect the items based on the conditions.

推荐答案

以下是一个如何用偶数和奇数分隔此列表的元素(数字)的示例:

Here is an example of how you could separate elements (numbers) of this list in even and odd numbers:

List<Integer> myList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

Map<Boolean, List<Integer>> evenAndOdds = myList.stream()
        .collect(partitioningBy(i -> i % 2 == 0));

你会得到这样的偶数/奇数列表(列表可能为空):

You would get lists of even/odd numbers like this (either list may be empty):

List<Integer> even = evenAndOdds.get(true);
List<Integer> odd = evenAndOdds.get(false);

您可以在 partitioningBy

这篇关于如何使用Java 8流将条件与条件分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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