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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar