Assume a list:
List<String> items = Arrays.asList("apple", "banana", "orange", "grape");
Approach 1: Using size()
String lastElement = items.get(items.size() - 1); System.out.println(lastElement);
Output:
grape
Approach 2: Using Streams
String lastElement = items.stream()
.reduce((first, second) -> second)
.orElse(null); // returns null if list is empty
System.out.println(lastElement);
Output:
grape
Summary:
- Using
get(size()-1)is simple and efficient. - Using
reduce()works in a functional style, especially for Streams. - Always handle empty lists to avoid
IndexOutOfBoundsException.
