How to separate lists by using conditions of Java 8 streams

Consider the following codes:

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 want to do here is to get even and odd values in a list from different lists

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

So I added this odd number to another list, and in another list I created it under other blocks

I know this is not an elegant way to use flow For example, if I use parallel streams, there will be thread safety problems in the odd list For performance reasons, I can't use different filters multiple times (it should be o (n))

This is just an example of a use case. The list can contain any object, and the lambda in the filter needs to separate them into separate lists according to some logic

Simply put: create multiple lists from a list that contain items separated based on certain conditions

Without a stream, it will just run a for loop, do a simple if else, and collect items according to conditions

Solution

The following is an example of how to separate the elements (numbers) of this list with even and odd numbers:

List<Integer> myList = Arrays.asList(1,10);

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

You will get such an even / odd list (the list may be empty):

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

You can pass any lambda that needs logic in partitionsby

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>