Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process object failed to satisfy the filter in java 8 stream

Tags:

java

java-8

I am trying to process object which is failed to satisfy the filter condition in the stream.

List<Integer> list = Arrays.asList(1,23,43,12,4,5);
list.stream().filter( i -> i > 10).collect(Collections.toList);

This will return a list of Object greater than 10. but I also want to process the objects which are unable to satisfy the condition (>10).

Thank You.

like image 831
Shivang Agarwal Avatar asked Dec 13 '22 15:12

Shivang Agarwal


2 Answers

Map<Boolean, List<Integer>> map = list.stream()
              .collect(Collectors.partitioningBy(i > 10));


map.get(false/true).... do whatever you want with those that failed or not
like image 136
Eugene Avatar answered Mar 15 '23 23:03

Eugene


I would just run two sweeps with stream() to get two different lists:

List<Integer> list = Arrays.asList(1,23,43,12,4,5);

List<Integer> largerThanTen = list.stream().filter( i -> i > 10)
                                 .collect(Collectors.toList());
List<Integer> smallerOrEqualToTen = list.stream().filter( i -> i <= 10)
                                .collect(Collectors.toList());

I think this is more readable than trying to do it in a one-liner, resulting in a less-idiomatic data structure.

like image 44
Mick Mnemonic Avatar answered Mar 16 '23 01:03

Mick Mnemonic