Reputation: 541
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?
Upvotes: 14
Views: 45627
Reputation: 49656
The ifPresent
method takes Consumer<? super T>
as a parameter. Simply speaking, it should be an action without return
statement. You could print the value if it's present, like
[...].ifPresent(System.out::print);
But it is not what about IDEA says. I think, you simply need to save an Option<Integer>
instance and then check it by isPresent
:
Optional<Integer> o = list.stream().min(Integer::compareTo);
if (o.isPresent()) {
smallest = o.get();
}
Of course, there are more convenient ways with orElse
:
smallest = o.orElse(Integer.MIN_VALUE);
or with the ternary operator:
smallest = o.isPresent() ? o.get() : Integer.MIN_VALUE;
Upvotes: 3
Reputation: 4342
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;
Upvotes: 10
Reputation: 309008
Here's how I'd do it:
package lambdas;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael
* Creation date 7/31/2016.
* @link https://stackoverflow.com/questions/38688119/java-8-streams-ifpresent
*/
public class MinimumExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
int smallest = list.stream().min(Integer::compareTo).orElse(Integer.MIN_VALUE);
System.out.println(smallest);
}
}
Upvotes: 10