How to separate a List by a condition using Java 8 streams

前端 未结 1 601
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 08:43

Consider the following code:

 List odd = new ArrayList();
 List even = null;  
 List myList = Arrays.         


        
相关标签:
1条回答
  • 2021-02-05 09:48

    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);
    

    You could pass any lambda with required logic in partitioningBy.

    0 讨论(0)
提交回复
热议问题