'how to filter a list only if the another list is not null

I'm trying to filter a list myList, but only if the another list choosenThings is NOT null.

Optionally: Check if it has at least one element.

myList - the base list I'm filtering

choosenThings - list with something data

myList.stream()
      .filter(e -> choosenThings.contains(e.getKindId()))
      .collect(Collectors.toList());

How can I do this? Is it possible to do this in filter?



Solution 1:[1]

How about:

if (choosenThings != null) {
    // your filtering logic
}

If all you have is streams, everything looks like a lambda...

Solution 2:[2]

myList.stream()
      .filter(e -> choosenThings == null || choosenThings.contains(e.getKindId()))
      .collect(Collectors.toList())

Solution 3:[3]

Why test chosenThings's reference for every element in the stream? Here's a variant on @Adriaan_Koster's solution:

Predicate<Element> predicate = 
    chosenThings == null ? e -> true: e -> chosenThings.contains(e);
myList.stream()
    .filter(predicate)
    .collect(Collectors.toList());

Solution 4:[4]

It is possible to do the null check in filter but ugly as hell:

myList.stream()
      .filter(e-> choosenThings != null ? choosenThings.contains(e.getKindId()) : true)
      .collect(Collectors.toList())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adriaan Koster
Solution 2 MikeFHay
Solution 3
Solution 4 Eritrean