6

I can only seem to find answers about last/first element in a list or that you can get a specific item etc.

Lets say I have a list of 100 elements, and I want to return the last 40 elements. How do I do that? I tried doing this but it gave me one element..

Post last40posts = posts.get(posts.size() -40);
Raul Chiarella
  • 518
  • 1
  • 8
  • 25
BananaBackend
  • 95
  • 1
  • 1
  • 13
  • 2
    Refer to http://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists. You can use `subList` from `size() - 40` to `size()` to get the last 40 elements. Also http://stackoverflow.com/questions/1279476/truncating-a-list-to-a-given-number-of-elements-in-java (or http://stackoverflow.com/questions/12099721/how-to-use-sublist) – Tunaki May 13 '16 at 21:16
  • What about `subList`? – x80486 May 13 '16 at 21:22
  • Possible duplicate of [Java: how can I split an ArrayList in multiple small ArrayLists?](https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists) – A Jar of Clay May 15 '19 at 14:52

3 Answers3

8

Do use the method sub list

List<Post> myLastPosts = posts.subList(posts.size()-40, posts.size());
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
6

(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
}
boly38
  • 1,806
  • 24
  • 29
1

Your code will give you only a single element. You need to use subList method like:

posts.subList(posts.size()-40, posts.size())