In this particular example, I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

    cars.stream()
        .filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

    cars.stream()
        .filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

    cars.stream()
        .filter(car -> Objects.nonNull(car))
        .map(car -> car.getName())
        .filter(carName -> Objects.nonNull(carName))
        .filter(carName -> carName.startsWith("M"))
        .collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

    cars.stream()
        .filter(Objects::nonNull)
        .map(Car::getName)        // Assume the class name for car is Car
        .filter(Objects::nonNull)
        .filter(carName -> carName.startsWith("M"))
        .collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

    cars.stream()
        .filter(car -> Objects.nonNull(car))
        .filter(car -> Objects.nonNull(car.getName()))
        .filter(car -> car.getName().startsWith("M"))
        .collect(Collectors.toList());
Answer from xbakesx on Stack Overflow
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-filter-null-values-from-a-stream
Java 8 – Filter null values from a Stream
We can use lambda expression str -> str!=null inside stream filter() to filter out null values from a stream. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> list = Arrays.asList("Java", ...
Top answer
1 of 7
541

In this particular example, I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

    cars.stream()
        .filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

    cars.stream()
        .filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

    cars.stream()
        .filter(car -> Objects.nonNull(car))
        .map(car -> car.getName())
        .filter(carName -> Objects.nonNull(carName))
        .filter(carName -> carName.startsWith("M"))
        .collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

    cars.stream()
        .filter(Objects::nonNull)
        .map(Car::getName)        // Assume the class name for car is Car
        .filter(Objects::nonNull)
        .filter(carName -> carName.startsWith("M"))
        .collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

    cars.stream()
        .filter(car -> Objects.nonNull(car))
        .filter(car -> Objects.nonNull(car.getName()))
        .filter(car -> car.getName().startsWith("M"))
        .collect(Collectors.toList());
2 of 7
95

You just need to filter the cars that have a null name:

requiredCars = cars.stream()
                   .filter(c -> c.getName() != null)
                   .filter(c -> c.getName().startsWith("M"));
Discussions

java - Filter Null items in Stream - Stack Overflow
When using a Java Stream, sometimes null values can occur after mapping. Currently when these values need to be omitted, I use: .stream() . element... More on stackoverflow.com
🌐 stackoverflow.com
Java stream filter null pointer issue - Stack Overflow
services = services.stream() .filter(service -> (service.getType().isEmpty() || service.getType().equals(type))) .collect(Collectors.toList()); where service.type is string, and type is also a string. My filter should return all services with its type equal to null (or simply blank), or the given type. ... java... More on stackoverflow.com
🌐 stackoverflow.com
Filter out null values in Java 8 stream filter expression so exception is not thrown - Stack Overflow
I have a Java 8 stream expression that has 3 filters and works fine. I want to guard against null pointer exceptions within the filters for most of the values. This is the expression: if(! More on stackoverflow.com
🌐 stackoverflow.com
ArrayList .addAll, how would I filter out null values?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
6
5
April 29, 2022
🌐
Oodlestechnologies
oodlestechnologies.com › blogs › filter-null-values-from-a-stream-in-java-8
Filter Null Values From a Stream In Java 8
February 14, 2020 - import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Examples { public static void main(String[] args) { Stream<String> vehicle = Stream.of("bus", "car", null, "bike", null, "train"); List<String> result = vehicle.filter(x -> x!=null).collect(Collectors.toList()); result.forEach(System.out::println); } }
🌐
Mkyong
mkyong.com › home › java8 › java 8 – filter a null value from a stream
Java 8 - Filter a null value from a Stream - Mkyong.com
August 10, 2016 - package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Examples { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php"); //List<String> result = language.collect(Collectors.toList()); List<String> result = language.filter(x -> x!=null).collect(Collectors.toList()); result.forEach(System.out::println); } } output ·
🌐
Techie Delight
techiedelight.com › home › java › filter null values from stream in java
Filter null values from Stream in Java | Techie Delight
July 7, 2026 - Many operations on streams will throw a NullPointerException if any null values are present in it. There are many options to handle null values in a stream: We know that Stream.filter() returns a stream consisting of the elements of the current ...
🌐
Javadeveloperzone
javadeveloperzone.com › java-basic › java-stream-filter-null-values
Java stream filter null values – Java Developer Zone
We can do it by filtering null elements from stream using Stream.filter(). Let’s go through the examples of Java stream filter null values from the steam of List, Map values and Set of Map.Entry
🌐
Benchresources
benchresources.net › home › java › java 8 – filter null and empty values from a stream
Java 8 - Filter null and empty values from a Stream - BenchResources.Net
September 8, 2022 - Filter null using Lambda Exp -" + " filter(num -> Objects.nonNull(num))\n"); result2.stream().forEach(System.out::println); // 4. filter null values from stream using Method References List<String> result3 = techStack .stream() .filter(Objects::nonNull) .collect(Collectors.toList()); // 4.1 print all String EXcluding null System.out.println("\n4. Filter null using Method Reference -" + " filter(Objects::nonNull)\n"); result3.stream().forEach(System.out::println); } } ... 1. Strings in Original Stream null Java Spring Hibernate null Python null 2.
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java streams › return non-null elements from java map operation
Return Non-null Elements From Java Map Operation | Baeldung
May 22, 2024 - However, we can use the filter() method in conjunction with the map() method to remove null elements from the resulting Stream.
🌐
Baeldung
baeldung.com › home › java › java streams › java null-safe streams from collections
Java Null-Safe Streams from Collections | Baeldung
May 11, 2024 - If a software development policy restricts the use of such a library, then this solution is rendered null and void. Java SE 8’s Optional is a single-value container that either contains a value or doesn’t.
🌐
Baeldung
baeldung.com › home › java › java streams › can stream.collect() return the null value?
Can Stream.collect() Return the null Value? | Baeldung
January 8, 2024 - Then, we collect the filtered null values in a List. It turns out that the two null elements are successfully collected in the result list. Therefore, null elements in the stream won’t cause the collect() method to return null. When we use the standard collectors, the collect() method of the Java ...
🌐
Java67
java67.com › 2023 › 10 › java-8-filter-example-example-with-null.html
Java 8 Stream.filter() example Example with Null and Empty String | Java67
You can write the code you feel better but when you use Stream pipeline, I think keeping condition simple improves readability. You can even combine multiple predicates to do more advanced filtering e.g. to filter all String which are null or empty you can do something like shown in above example but you are free with conditions, you can use whatever condition you want.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Java 8 Filter Null Values from a Stream Example - Java Code Geeks
February 25, 2019 - A stream is a sequence of elements that support the sum operations. In this tutorial, we will learn how to filter the null elements from a Stream in Java.
🌐
Medium
medium.com › @rtj1857 › check-nulls-in-java-stream-ae84dc81c5fa
Check nulls in Java Stream. In the previous blog we got to know… | by Ramit Raj | Medium
September 5, 2023 - public List<String> fetchNames(List<Student> studentList){ List<String> namesList= checkStream(studentList).filter(Objects::nonNull) .map(student->student.getNames()).collect(Collectors.toList()); return namesList; } In this case if null present it will be taken care of and no exception will be thrown. Happy Learning. Thank you! Java ·
🌐
Code2care
code2care.org › home page › java-programs › filter out null values using java 8 stream api
How to filter null values using Java 8 Stream API | Code2care
February 27, 2024 - We can make use of the intermediate filter() operation on a stream to filter out the null values as follows. Example: import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Main { public static void main(String[] ...
🌐
DEV Community
dev.to › monknomo › filter-null-values-from-a-list-with-java8-lambda-351h
Filter Null Values from a List with Java8 Lambda - DEV Community
June 10, 2018 - Remove null values from a Collection, like an ArrayList or Set with a Java Lambda. Tagged with java, functional, java8.
Top answer
1 of 2
1

The attributes such as the billingMethod, whenever it is possibly null inside the List, it should still work for comparison to get distinct values. On the other hand, comparing them with some other String constant can be solved in the manner the user FilipRistic suggested.

But, when it is about objects which could be possibly null and you want to access the inner attributes further down safely, you can make use of Optional and chain the accessors. For a sample amongst those, while you want to access the numberCode of your destination which could possibly be null, you can have an accessor in PurchasedTripSegment class to expose this:

Optional<Integer> getDestinationCode() {
    return Optional.ofNullable(this.getDestination()) // empty for 'null'
                   .map(Node::getNumberCode);
}

With similar changes for other accessors, your overall code would update and change to something like:

filteredList = purchasedTripSegments.stream()
        .filter(segment -> PurchasedVendorType.RAIL.equals(segment.getVendorType()))
        .filter(distinctByKey(segment -> Arrays.asList(segment.getBillingMethod(),
                segment.getOriginCode(), segment.getDestinationCode(),
                segment.getStopOffLocationCode())))
        .filter(segment -> segment.getBillingMethod().equalsIgnoreCase(BILLING_METHOD_LOCAL) ||
                (segment.getBillingMethod().equalsIgnoreCase(BILLING_METHOD_RULE) &&
                        segment.getDestinationCode().equals(segment.getStopOffLocationCode())))
        .collect(Collectors.toList());
2 of 2
1

No there isn't any way for filter to know that since it doesn't know in which way you will use element inside Predicate, your only solution is to perform the check for null yourself.

Note that you can avoid check in cases where you are comparing to constant that you know isn't null, instead of writing:

segment.getBillingMethod().equalsIgnoreCase(BILLING_METHOD_LOCAL)

You could write it like this:

BILLING_METHOD_LOCAL.equalsIgnoreCase(segment.getBillingMethod())

This will avoid NPE but it only helps you in few cases not all of them, for other cases you will have to perform check or maybe refactor to return type Optional and your condition could look something like this:

segment.getDestination()
    .flatMap(d -> segment.getStopOff()
        .map(s -> s.getStopOffLocation)
        .filter(s -> s.getNumberCode() == d.getNumberCode()) )
    .isPresent();
🌐
ZetCode
zetcode.com › java › streamfilter
Java Stream filter - filtering Java streams
The filter method accepts an anonymous functions that returns a boolean true for all elements of the stream whose length is bigger that five. ... We go through the result with the forEach method and print all its elements to the console. $ java Main.java custom orphanage forest bubble butterfly · The next example filters out null values.