b>j)΄!Pԫ&;"kB޶}pSVT(wę!j x;-m@JnQ+պכ7MajfJͱ4jѲ撆RxZMz7vIW/dٞТזcZM~ji ߒsQzԠDW3Den"M+/B:-uIJ7j委9p='mANޭ=/B:-n&nUfqxZM~c Ϲ+,&ᾺܢF[(1*" ϒ"Jԧ<;b" "jܢF[x ,!q қ*]/؝27SMcs"ޭDQ/应ܢF_! :s" 7`F+SVTn"IJnQ/应B 4 wD"IJ׭-`S9DrjiEJ߅gJ应矁[xZM~n"IB؃!'Тѕ+(mIKʭ/|ϐܢF[xZMzG %嬩/c[[ Java - Get the last element of a list - Mkyong.com

Java – Get the last element of a list

In Java, index starts at 0, we can get the last index of a list via this formula: list.size() - 1

JavaExample1.java

package com.mkyong.test;

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

public class JavaExample1 {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        System.out.println(list.get(list.size() - 1));
        System.out.println(list.get(list.size() - 2));
        System.out.println(list.get(list.size() - 3));
        System.out.println(list.get(list.size() - 4));
        System.out.println(list.get(list.size() - 5));
        
    }

}

Output


5
4
3
2
1

Python has reverse indexing, where -1 refer to the last element of a list, hope Java can implement it in the future release, then we can simplify the code like this:


	List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

	System.out.println(list.get(-1)); // 5
	System.out.println(list.get(-2)); // 4
	System.out.println(list.get(-3)); // 3
	System.out.println(list.get(-4)); // 2
	System.out.println(list.get(-5)); // 1

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jurijs Infinite Code
4 years ago

Java is not Pyhton. You can also you Iterables.getLast() from google commons…

I-G
4 years ago

Helpful to remember how it was. Thanks