logo
  • Home
  • Contact
💵
Should I be buying I-Bonds in 2023?
💰
Need a step-by-step guide to opening your Roth IRA?
Buy me a coffee Buy me a coffee
aws c++ career cli css docker finance git java js misc python sql

How to Filter Null Values from a Stream in Java


Suppose we are streaming through a list of objects in Java.

List<String> lst = ...;

How can we filter for only non-null objects?

1. Using java.util.Objects

java.util.Objects has a method Objects::nonNull that will do just this.

lst.stream().filter(Objects::nonNull);

This is just a shorthand for the following:

lst.stream().filter(obj -> Objects.nonNull(obj));

2. Using a comparison operator

We can also simply check that an object does not equal null.

lst.stream().filter(obj -> obj != null);

Related in Java

How to Extract String Between Parentheses in Java
How to Run Tasks in Parallel with ExecutorService and CompletableFuture in Java
How to Check if a Date is Between Two Dates in Java (Date, LocalDate, Instant)
How to Split by Vertical Pipe Symbol "|" in Java
How to Get All Appenders in Logback Context in Java
How to Convert from Date to LocalDate in Java
How to Retry a Task in Java using Guava's Retryer
How to Convert Between Millis, Minutes, Hours, Days (and more) in Java
How to Ignore Generated Files in IntelliJ's Find in Files (Search Bar)
How to Check If a List Contains Object by Field in Java
How to Get Part of an Array or List in Java
What is the double colon (::) in Java? It's just a method reference!
How to Check If a File Exists in Java
How to Convert an InputStream to a File in Java
How to Convert a List<Long> to List<Integer> in Java (or vice versa!)
How to Get Current Timestamp (Epoch) in Milliseconds in Java
© , LogFetch   âˆ™   Advertise Here   âˆ™   Privacy Policy