Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last three elements from a List/ArrayList? [closed]

Tags:

java

I need to get the last three elements added to a List. Are there any utility methods for this or will I just use a for loop that iterates down from "size(myList) - 1"?

like image 245
sonicboom Avatar asked Jan 30 '13 14:01

sonicboom


People also ask

How do I remove the last 3 elements from a list in Java?

We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.

How do I get the last position of an ArrayList?

Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

What is the last index of an ArrayList?

The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter.

Is ArrayList last in first out?

Arraylist will hold the last element added at the end of the list. So it keeps the order of insertion. But it's a random access container, it doesn't really have a sense of first in first out. As a side note, just based on the way that ArrayList works internally, it wouldn't be a good idea to use it as a FIFO queue.


2 Answers

You could use List.subList() to get a view onto 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 when l contains fewer than three elements.

like image 166
NPE Avatar answered Oct 12 '22 23:10

NPE


See:

List.subList(arg0, arg1)!
like image 37
Bob Flannigon Avatar answered Oct 13 '22 00:10

Bob Flannigon