Java – get the last three elements from list / ArrayList?
•
Java
I need to add the last three elements to the list Is there any practical way, or do I just use a for loop that iterates down from "size (mylist) – 1"?
Solution
You can use list Sublist() to view the end of the original list:
List<E> tail = l.subList(Math.max(l.size() - 3,0),l.size());
Here, when l contains less than three elements, math Max() handles this situation
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码