How can I consume for each elements of an optional list?

java 8 optional<list example
java optional
which element of a class is optional
convert optional to list
convert optional object to list java
optional flatmap
java optional ifpresent
optional collection java

I have a List which can be null;

List<T> list; // may or may not null

I want to process for each element with a consumer.

So far, I do.

ofNullable(list)
        .map(List::stream)
        .ifPresent(stream -> stream.forEach(e -> {}));

or

ofNullable(eventDataList).ifPresent(v -> v.forEach(e -> {}));

Is there any easy or concise way to do this?

To avoid ugly null checking, use orElse(Collections.emptyList())

Optional.ofNullable(eventDataList)
        .orElse(Collections.emptyList())
        .forEach(e -> {});

With static imports, it's pretty concise:

ofNullable(eventDataList).orElse(emptyList()).forEach(e -> {});

The Java Tutorial: A Short Course on the Basics, LinkedList implements all optional list operations; null elements are allowed in The LinkedList implementation consumes more memory than the ArrayDeque  The FDA recommends using the AOAC Official Method of Analysis 996.06 to determine the total fat per serving. 4 If the total fat is less than 0.5 grams per serving, it can be expressed as zero on the nutrition label, but it still must be listed. 4. Saturated Fat “Saturated” fat is the sum of all fatty acids containing no double bonds.

Technically, if (list != null) { list.stream().forEach(e -> {...}); } is both shorter and more efficient in terms of CPU/memory usage than your variants.

Architecturally, if you have control over initialization of the list and its usage, it's often better to use either Collections.emptyList() instead of null (if the logic of your program allows) or make the list Optional from the very beginning. That would save you from necessity to make checks or create Optionals every time you want to use the list.

Working With Java 8 Optionals, How to work with Java 8 Optional methods for maximum data safety. Adding Element to as List or Collection If the value is present the provided Consumer will be invoked with the value contained as a parameter. Java LinkedList class is doubly-linked list implementation of the List and Deque interfaces. It implements all optional list operations, and permits all elements (including null). It implements all optional list operations, and permits all elements (including null).

I'm not sure that you can make it more concise. However, if you are frequently using the construct of looping over a nullable list and consuming each element, you could make a small class which does just that:

public class ListConsumer {
    public static <H> Consumer<List<H>> of(Consumer<H> consumer) {
        return hs -> hs.forEach(consumer);
    }
}

You can then consume each element in a list as follows (e.g. print all Strings in list):

List<String> list = Arrays.asList("A", "B", "C");

Consumer<String> consumer = System.out::println;
Optional.ofNullable(list).ifPresent(ListConsumer.of(consumer));

Java 8 Optional Usage and Best Practices, Check out this post where we look at Optional, first introduced in to do explicit null check for each reference, as shown below, and we all If you are new to Java 8, then you are probably wondering: What is a consumer? In the case of list and stream sequences, the for form itself does not keep each element reachable. If a list or stream produced by a seq-expr is otherwise unreachable, and if the for body can no longer reference an id for a list element, then the element is subject to garbage collection.

Model-Driven Engineering and Software Development: 7th , means the element is kept in any configuration, and, thus, e.g., the compilation for a model element with an optional features needs to get a refined annotation. strategy does not consume significantly more runtime for iterating the list of the fact that for each element missing an annotation its list of children elements is​  The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all.

26 Reasons Why Using Optional Correctly Is Not Optional, Sometimes, when an Optional value is not present, all you want to do is to ifPresent() is a good alternative for isPresent()-get() pair when you just need to consume the value. public Optional<List<String>> fetchCartItems(long id) { This method creates a Stream of one element or an empty Stream (if  Term Definition; element: Required in the For Each statement. Optional in the Next statement. Variable. Used to iterate through the elements of the collection. datatype: Optional if Option Infer is on (the default) or element is already declared; required if Option Infer is off and element isn't already declared.

java.util.Optional.ifPresent java code examples, public void forEach( BiConsumer<String,URI> consumer ) { entries.stream().​collect( Collectors.groupingBy( e -> e.key ) ) .forEach( ( key, list ) -> list.stream()  The list of vitamins and minerals below can give you an understanding of how particular different types of vitamins and minerals work in your body, how much of each nutrient you need every day , and what types of food to eat to ensure that you are getting an adequate supply.

Comments
  • why not simply if (list != null) { list.foreach(e->{});} ? Functional programming style is cool but not necessary to be always cleaner and more readable.
  • @AdrianShum Because I've already known that. Thanks.
  • I like that CPU/MEM concern. +1
  • I know this answer was given in 2016 before Java 9 so now, it can be handled using the native of() which would create an immutable list. I don't think it's good practice to allow an immutable list to be modified by adding elements to it.