Stefan B Stefan B - 4 months ago 17
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<>();
list.add(1);
list.add(2);
list.add(3);
int smallest = list.stream().min(Integer::compareTo).get();
System.out.println(smallest);


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

int smallest = list.stream().min(Integer::compareTo).ifPresent(integer -> 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

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

 Optional<Integer> minimal = list.stream().min(Integer::compareTo);

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;