Java 8 : findAny and findFirst Operations

Spread the love

In the below code example, we would see the usage of the 2 operations provided in Java 8 namely findAny and findFirst

import java.util.*;
import java.util.stream.*;

public class Java8GroupByExample {
    public static void main(String args[]) {
      
     List<Integer> numList = Java8GroupByExample.getNumbersList();
     Integer first = numList.stream().findFirst().get();
     Integer any = numList.stream().findAny().get();
     
     System.out.println(first);
     System.out.println(any);
      
    }
    
    private static List<Integer> getNumbersList(){
        
        List<Integer> list = new ArrayList<Integer>();
        list.add(5);
        list.add(12);
        list.add(9);
        list.add(15);
        list.add(25);
        list.add(4);
        
        return list;
    }
    
}