How to get the last element of a List in Java

The last Element from an list can be accessed using the size of a list minus 1. You need also need to test if the list is empty.

Call the following method:

list.get(list.size() - 1);

Example:

The following code creates a List using 4 elements, then create the lastElement reference and sets it to null. If the list is not empty, the element at the position size -1 is set in the lastElement. The output is then displayed.

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

public class ListLastElement {

	public static void main(String[] argv){
		
		List<String> list = Arrays.asList( "A", "B", "C", "D" );
		
		String lastElement = null;
		if( !list.isEmpty() )
			lastElement = list.get(list.size() - 1);
		
		System.out.print( "The last element is " + lastElement);
	}
	
}

The output will be:

The last element is D

References:

Java 8

Recent Comments