java stream find match or the last one?

  • A+

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.


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()); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: