Search code examples
javafilterjava-8java-streamcollectors

Is there a nice way to filter a list using streams and get a list of the items or null if no item passed the filter?


Currently I do:

List<MyObj> nullableList = myObjs.stream().filter(m -> m.isFit()).collect(Collectors.toList());
if (nullableList.isEmpty()) {
    nullableList = null;
}

Is there a nicer way? Something like Collectors.toListOrNullIfEmpty()?


Solution

  • I'm not actually sure you have to do that way. Sometimes people write horrible code trying to make it simpler. I'd leave this case with additional if after stream like in your code. But you can find a code you looking for below c:

    public class Demo {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1, 2, 3, 4);
            List<Integer> nullableList = list.stream()
                    .filter(m -> m > 2)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toList(), filtered -> filtered.isEmpty() ? null : filtered
                    ));
            System.out.println(nullableList);
        }
    }