[Java](EN) Difference between get(0) and findFirst() in Java List
Environment and Prerequisite
- Java
Difference
get(0) in List
- Return the first element
- Throw
IndexOutOfBoundsException
when first element is empty
List<String> myList = Arrays.asList("1", "2", "3");
String firstElement = myList.get(0);
findFirst() in Stream
- Return the first element that meets the given condition and if there is no element satisfying that condition then return
Optional.empty()
- Available after Java 8
List<String> myList = Arrays.asList("1", "2", "3");
Optional<String> firstElementOptional = myList.stream().findFirst();
if (firstElementOptional.isPresent()) {
String firstElement = firstElementOptional.get();
}
Keep in Mind
- In data structures like List, let’s make code to handle exceptions such as
IndexOutOfBoundsException
orNullPointerException
when accessing the first or other elements.