如何使用 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
,流收集器将收集它们.
对于奇怪的情况,过滤器将返回 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
中传递任何具有所需逻辑的 lambda.
You could pass any lambda with required logic in partitioningBy
.
相关文章