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

Viewed 278

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?

4 Answers

How about:

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

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

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

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

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())
Related