How to handle Null Values in Java8 Streams? wpaccuracy.com

please click here for more wordpress cource

Handling null values in Java 8 streams can be done in different ways depending on what you want to achieve.

One approach is to filter out null values from the stream using the filter() method. Here’s an example:

List<String> strings = Arrays.asList("apple", null, "banana", null, "cherry");
List<String> nonNullStrings = strings.stream()
                                     .filter(s -> s != null)
                                     .collect(Collectors.toList());

In this example, the filter() method is used to remove the null values from the stream, resulting in a new list of non-null strings.

Another approach is to use the map() method to replace null values with a default value. Here’s an example:

List<String> strings = Arrays.asList("apple", null, "banana", null, "cherry");
List<String> nonNullStrings = strings.stream()
                                     .map(s -> s == null ? "unknown" : s)
                                     .collect(Collectors.toList());

In this example, the map() method is used to replace null values with the string “unknown”.

It’s important to note that if you’re working with streams of primitive types, such as int or double, you can’t use null values. In that case, you can use the Optional class to represent the absence of a value.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *