Im trying to understand streams right now. I'd like to save the highest number from a stream as an Optional, but the program only allows me to save it as an Integer. Since it's possible that the stream is empty, so there is not highest value, i'd like to be able to save it as an Optional.
I've tried this so far:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;
public class StreamsTest {
public static void main(String[] args) {
Collection<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
Stream<Integer> stream1 = list.stream().filter(x -> x % 2 == 1);
if (stream1.findAny().isPresent() == true)
System.out.println("Hey");
Optional<Integer> opt = stream1.max(Comparator.comparing(Integer::valueOf)).get();
}
}
Is it because of the .get()? I could imagine that when i use it, the program expects to get a value. If it doesnt get a value it already crashes at this point and there is no need to try to save it to a variable. So it either gets a value and saves it in an Integer variable or it crashes since .get() cant deliver the input for an Optional.