Reducing the size of List in Java

I had a List that had around 70000 objects in it and I needed only the first 15000. I was about to create a new empty array list and iterate 15000 times over the current one in order to get a smaller list. That would have been a mess.

I searched a bit and realized there was an easier (and I’m hoping it’s more efficient) way to reduce the size of a list.

//templist has 70000 objects in it

tempList.subList(15000 – 1, tempList.size()-1).clear();

//templist now has the first 15000 objects in it

//15000 – 1 because the positions start from 0

 

Tags: , , ,

Leave a comment