Filter and then find the first or returnt the default value

Description

The following code shows how to filter and then find the first or returnt the default value.

Example


//from  w w  w.  j a va2  s .c om
import java.util.Arrays;
import java.util.List;

public class Main {
   public static void main(String[] args) {
     List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
     int i = numbers.stream().filter(n -> n % 2 == 0).findFirst().orElse(-1);

     System.out.println(i);
   }

}

The code above generates the following result.





















Home »
  Java Streams »
    Examples »




Average
Filter
Group
IntStream
Map
Partition
Reduce
Sort
Sum