How to get the last element of a List in Java?

There are many way to get last element from a list in Java.

In first scenario we are using java 8 reduce method,here reduce operation applies to each element in the stream where the first argument to return the previous value and second argument is the current stream element if element not found then use orElse method to print there are not any last element.

In Second scenario List come with a method called get() which takes in a position as a parameter that represents the index of the element you want returned so there are passing index = size – 1.

In third scenario we are using java 8 skip method.here we find size of list data in skip method and call to findFirst to convert Stream to String.if element not found then use orElse method to print there are not any last element.

				
					import java.util.Arrays;
import java.util.List;

public class FindLastElement {
	public static void main(String[] args) {

		List<String> list = Arrays.asList("java", "Spring", "JSP", "Hibernate");
		// using reduce method
		String result = list.stream().reduce((first, second) -> second).orElse("not any last element");
		System.out.println("first way output :- " + result);

		// using size method
		String str = 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("not any last element");
		System.out.println("third way output :- " + strData);

	}
}
				
			

Output :-
first way output :- Hibernate
second way output :- Hibernate
third way output :- Hibernate

Leave a Comment

Your email address will not be published. Required fields are marked *