java get the first element of the list

www.la‮ruttu‬i.com
java get the first element of the list
/**
 * @author lautturi.com 
 * Java example: get the first element in java list
 */


import java.util.*;

public class Lautturi {

	public static void main(String[] args) throws Exception {
		
		List<Integer> list = new ArrayList<Integer>();
		list.add(3);
		list.add(7);
		list.add(15);
		list.add(8);
		
		Integer firstElement = list.stream()
				  .findFirst()
				  .orElse(null);  //Give a value null if there are no elements

		System.out.println(firstElement);
		
		Integer firstEle = list.stream()
				  .findFirst()
				  .orElseThrow(() -> new Exception()); //Throw an exception if there are no elements  
		
	}
}

output:

3
Created Time:2017-09-26 15:16:14  Author:lautturi