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?
The ifPresent method of the Optional class is an instance method that performs an action if the class instance contains a value. This method takes in the Consumer interface's implementation whose accept method will be called with the value of the optional instance as the parameter to the accept method.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
If you just want an Optional returning false for isPresent() , you don't need to mock the Optional at all but just create an empty one. Of course this test only tests that the mock object actually returns the stubbed return value, but you get the idea.
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);
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With