Getting the last three elements from a List / ArrayList?

I need to add the last three items to the list. Are there any utility methods for this, or am I just using a for loop that iterates with "size (myList) - 1"?

+3


source to share


6 answers


You can use List.subList()

to get an idea of ​​the tail of the original list:

List<E> tail = l.subList(Math.max(l.size() - 3, 0), l.size());

      



Here Math.max()

takes care of the case where it l

contains less than three elements.

+26


source


See:



List.subList(arg0, arg1)!

      

+6


source


Use List.subList

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/List.html#subList%28int,%20int%29

Something like

myList.subList(myList.size()-3, myList().size());

      

+2


source


try

    List list = Arrays.asList(1, 2, 3, 4);
    ListIterator i = list.listIterator(list.size());
    while (i.previousIndex() != list.size() - 4) {
        Object e = i.previous();
        System.out.print(e + " ");
    }

      

prints

4 3 2

      

+2


source


how about subList(from, to)

?

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/AbstractList.html#subList(int , int)

+1


source


Maybe java.util.Stack

more helpful here . What is the use of your list?

0


source







All Articles