Jin Kwon Jin Kwon - 4 months ago 10
Java Question

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

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?

Answer

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.