How to get the first element of a stream in Java

2 Answers

0 votes
import java.util.*; 

public class MyClass {
    public static void main(String args[]) {
        List<Integer> list = Arrays.asList(4, 5, 7, 8, 19); 
  
        Optional<Integer> oi = list.stream().findFirst(); 
 
        if (oi.isPresent()) { 
            System.out.println(oi.get()); 
        } 
        else { 
            System.out.println("empty"); 
        } 
    }
}



/*
run:

4

*/

 



answered Oct 3, 2019 by avibootz
edited Oct 3, 2019 by avibootz
0 votes
import java.util.*; 

public class MyClass {
    public static void main(String args[]) {
        List<Integer> list = Arrays.asList(); 
  
        Optional<Integer> oi = list.stream().findFirst(); 
 
        if (oi.isPresent()) { 
            System.out.println(oi.get()); 
        } 
        else { 
            System.out.println("empty"); 
        } 
    }
}



/*
run:

empty

*/

 



answered Oct 3, 2019 by avibootz

Related questions

...