How to filter non-null value in Java?

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 02-May-2019 08:30:50
Advertisements