Search code examples
javalistlambdajava-8java-stream

Find matching element using a Java stream if one exists, else the last one?


How to find the first match or the last element in a list using the Java Stream API?

This means that if no element matches the condition, the last element should be returned.

e.g.:

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?


Solution

  • Given the list

    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    

    You could just do :

    int value = list.stream().filter(x -> x == 2)
                             .findFirst()
                             .orElse(list.get(list.size() - 1));
    

    Here if the filter evaluates to true the element is retrieved, else the last element in the last is returned.

    If the list is empty you could return a default value, for example -1.

    int value = list.stream().filter(x -> x == 2)
                             .findFirst()
                             .orElse(list.isEmpty() ? -1 : list.get(list.size() - 1));