/** * @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