There are multiple ways to get the last element from a List in Java 8.
Using Java 8 reduce() Method :
- The reduce() method is part of the Stream API .
- It processes each element in the stream one by one.
- In the lambda expression:
- The first parameter (first) represents the previous value.
- The second parameter (second) represents the current element.
- The logic (first, second) -> second ensures that the latest element replaces the previous one, resulting in the last element.
- It returns an Optional:
- Use orElse() to provide a default value if the list is empty.
Using get() Method with size() :
- The List interface provides the get(index) method.
- The size() method returns the total number of elements in the list.
- Since indexing starts from 0, the last element is located at: size() – 1
- Always check if the list is empty before accessing:
- To avoid IndexOutOfBoundsException.
Using Java 8 skip() Method :
- The skip(n) method is used to skip the first n elements of a stream.
- To get the last element:
- Skip size() – 1 elements.
- After skipping:
- Use findFirst() to get the remaining (last) element.
- It returns an Optional:
- Use orElse() to handle the case when the list is empty.
import java.util.Arrays;
import java.util.List;
public class FindLastElement {
public static void main(String[] args) {
List list = Arrays.asList("java", "Spring", "JSP", "Hibernate");
// using reduce method
String result = list.stream().reduce((first, second) -> second)
.orElse("No Element Found");
System.out.println("first way output :- " + result);
// using size method
String str = list.isEmpty() ? null : list.get(list.size() - 1);
System.out.println("second way output :- " + str);
// third skip method
String strData = list.stream().skip(list.size() - 1).findFirst()
.orElse("Now Element Found");
System.out.println("third way output :- " + strData);
}
}
Output :-
first way output :- Hibernate
second way output :- Hibernate
third way output :- Hibernate