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

前端 未结 1 602
伪装坚强ぢ
伪装坚强ぢ 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 myList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    
    Map> 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 even = evenAndOdds.get(true);
    List odd = evenAndOdds.get(false);
    

    You could pass any lambda with required logic in partitioningBy.

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