Stefan B Stefan B - 1 year ago 133
Java Question

Java 8 streams "ifPresent"

I am trying to learn about streams and encountered a problem:
I want to get the minimal value of a list and assign it to an int variable.
For that I did the following:

List<Integer> list = new ArrayList<>();
int smallest =;

This works well and i get
as a result.
The issue is that the IDE gives the warning that
is called before checking for
To fix that i used the slightly different
method and tried the following:

int smallest = -> integer);

Unfortunately this doesn't work since I get the warning:
Bad return type in Lambda, Integer cannot be converted to void.

My question finally is: How can I assign the min value to the
int smallest
variable WITH checking ifPresent?

Answer Source

Stream#min return Optional of result because in general stream can be empty so there can be no minimal value.

 Optional<Integer> minimal =;

To get value from Optional you need to have some fallback value

Integer absent = Integer.MIN_VALUE;

The easiest would be to use orElse

Integer smallest = minimal.orElse(absent);

Little bit longer would be isPresent

Integer smallest = minimal.isPresent() ? minimal.get() : absent;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download