Jin Kwon Jin Kwon - 1 year ago 79
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.

.ifPresent(stream -> stream.forEach(e -> {}));


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

Is there any easy or concise way to do this?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download