CodexBloom - Programming Q&A Platform

Java 17 scenarios with Optional and Stream for Filtering Null Values in Collections

👀 Views: 247 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
java stream optional Java

I'm having trouble with I'm working with an scenario when trying to filter out null values from a List using Java 17's Stream API combined with Optional. I have the following code that is supposed to return a list of non-null values, but it seems to skip all entries, resulting in an empty list. Here's the code snippet: ```java import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> items = Arrays.asList("apple", null, "banana", null, "cherry"); List<String> filteredItems = items.stream() .map(Optional::ofNullable) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); System.out.println(filteredItems); } } ``` Despite expecting to see `["apple", "banana", "cherry"]`, the output is an empty list. I've tried simplifying the filtering step by directly checking for null values, but that didn't yield the expected result either. Here's the alternative approach I attempted: ```java List<String> filteredItems = items.stream() .filter(item -> item != null) .collect(Collectors.toList()); ``` This still results in an empty list, even though I can confirm that the input list does contain non-null values. I suspect there might be an scenario with how the stream is being processed in this context. Can anyone provide insights on why this is happening and what the correct approach would be to filter out null values in this scenario? Any help would be appreciated!