views:

521

answers:

3

There is any method to truncate a list in java, for example, to the first 100 elements, discarding the others? (I mean, without iterating and/or copying/deleting elements one by one)

+5  A: 
list.subList(100, list.size()).clear();

or:

list.subList(0, 100);
karim79
+5  A: 

Try

List<String> items = Arrays.asList("1", "2", "3");
List<String> subItems = items.subList(0, 2);

You should bear in mind that subList returns a view of the items, so if you want the rest of the list to be eligible for garbage collection, you should copy the items you want to a new List:

List<String> subItems = new List<String>(items.subList(0, 2));
Ben Lings
while the question is not exactly clear, it does sound like sam wants a the end of the list deleted. Therefore your answer should include a list.clear().
mP
This is not likely to perform as well as karim79's solution, which is the best alternative - it has the best chance of performing well and is the cleanest code as well.
Software Monkey
I think it depends on the number of elements to be removed (and also if the List supports modification)
Ben Lings
+2  A: 

You did not specify the type of list. If it is an ArrayList, then

list.removeRange(100, list.size());

has cost O(1).

On the other hand, if it is a LinkedList, then removeRange will require O(list.size()) calls, and so clear() (it calls removeRange()). There appears to be no O(1) way to truncate a linked list in java, except for writing your own implementation. If the list is short, copying and losing the old reference, as suggesting by Ben Lings, is the fastest way to get what you want.

tucuxi
@tucuxi: "There appears to be no O(1) way to truncate a linked list in java". Don't blame Java. It is a fundamental property of singlely linked lists.
Stephen C
removeRange is protected
Ben Lings
Or removeRange really O(1)? It has to either null the removed elements in the backing array or copy the retained elements to a new backing array.
Ben Lings
@Ben: nulling 100 elements of an ArrayList with N elements is O(1). No copying is actually performed in this case. (I checked the OpenJDK code!)
Stephen C
Doesn't it have to null all the removed elements (not the 100 that are being retained)?
Ben Lings
@Stephen C - yes, but it should be possible to truncate an N-element list at the Kth element in O(K). In Java's implementation, it requires O(N) instead. I did not express myself clearly.If it is an ArrayList, Karim's answer is perfect.
tucuxi