To get the first non-null element from a list in Java, you can use the stream
API and the filter
and findFirst
methods.
Here is an example using a list of strings:
List<String> list = Arrays.asList(null, "abc", null, "def", "ghi"); String firstNonNull = list.stream() .filter(Objects::nonNull) .findFirst() .orElse(null);Source:wwtual.wturi.com
The stream
method converts the list into a stream, which allows you to apply various operations to the elements. The filter
method filters out null elements, and the findFirst
method returns the first non-null element in the stream (wrapped in an Optional
). The orElse
method is used to provide a default value if the stream is empty (i.e. there are no non-null elements in the list).
In this case, the firstNonNull
variable will be assigned the value "abc".
Note that this approach will only work if the list is not modified after the stream is created. If the list may be modified, you may need to use a different approach to ensure that the first non-null element is returned.