java list get first element
final Object firstElement = list.stream() .findFirst() .orElse(new Object()) //Give a default value if there are no elements final Object firstElement = list.stream() .findFirst() .orElseThrow(() -> new Exception()) //Throw an exception if there are no elements
Here is what the above code is Doing:
1. We’re creating a list of strings.
2. We’re creating a stream from the list.
3. We’re using the findFirst() method to get the first element of the stream.
4. We’re using the orElse() method to provide a default value if the stream is empty.
5. We’re using the orElseThrow() method to throw an exception if the stream is empty.