- A+
Category:Languages
How to find the first match or the last element in a list using java stream?
Which means if no element matches the condition,then return the last element.
eg:
OptionalInt i = IntStream.rangeClosed(1,5) .filter(x-> x == 7) .findFirst(); System.out.print(i.getAsInt());
What should I do to make it return 5;
You can use reduce()
function like that:
OptionalInt i = IntStream.rangeClosed(1, 5) .reduce((first, second) -> first == 7 ? first : second); System.out.print(i.getAsInt());