The following is part of the List interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.
The following is part of the List interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.
There isn't an elegant way in vanilla Java prior to Java 21.
Google Guava
The Google Guava library is great - check out their Iterables.getLast() method. This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException, as with the typical size()-1 approach - I find a NoSuchElementException much nicer, or the ability to specify a default:
lastElement = Iterables.getLast(iterableList);
You can also provide a default value if the list is empty, instead of an exception:
lastElement = Iterables.getLast(iterableList, null);
or, if you're using Options:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
Do use the method sub list
List<Post> myLastPosts = posts.subList(posts.size()-40, posts.size());
(To complete Ankit Malpani answer)
If 40 is provided by our lovely users, then you will have to restrict it to the list size:
posts.subList(posts.size()-Math.min(posts.size(),40), posts.size())
Another way to show it:
@Test
public void should_extract_last_n_entries() {
List<String> myList = Arrays.asList("0","1","2","3","4");
int myListSize = myList.size();
log.info(myList.subList(myListSize,myListSize).toString()); // output : []
log.info(myList.subList(myListSize-2,myListSize).toString()); // output : [3, 4]
log.info(myList.subList(myListSize-5,myListSize).toString()); // output : [0, 1, 2, 3, 4]
int lastNEntries = 50; // now use user provided int
log.info(myList.subList(myListSize-Math.min(myListSize,lastNEntries),myListSize).toString());
// output : [0, 1, 2, 3, 4]
// log.info(myList.subList(myListSize-lastNEntries,myListSize).toString());
// ouch IndexOutOfBoundsException: fromIndex = -45
}