How to filter non-null value in Java?


Let’s say the following is our List with string elements:

List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL");

Now, create a stream and filter elements that end with a specific letter:

Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L"));

Now, use Objects::nonnull for non-null values:

List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());

The following is an example to filter non-null value in Java:

Example

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL");
      Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L"));
      List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());
      System.out.println("League names ending with L = "+list);
   }
}

Output

League names ending with L = [BBL, IPL, FPL, NFL]

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements