Back to questions
JuniorTheoryCommon
What does the program print?
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> xs = List.of(1, 3, 5);
int r = xs.stream()
.filter(x -> x % 2 == 0)
.findFirst()
.orElse(-1);
System.out.println(r);
}
}-1
- Expecting
0: an emptyOptionalhas no value of its own, not even zero;orElse(-1)returns the fallback that was passed to it. - Expecting a
NoSuchElementException: onlyget()throws on an emptyOptional, whileorElsereturns the fallback.
- What would
findFirst().get()do in this program? - What does the program print for the list
List.of(1, 4, 6)?