SomethingSomething SomethingSomething - 23 days ago 7
Java Question

Java: remove a range of indices from a list

Consider a linked list of strings I got from somewhere

LinkedList<String> names = getNames();


Now, I want to remove the first k elements from the list. Currently, I'll do it this way:

for (int i = 0 ; i < k ; i++) {
names.removeFirst();
}


Is there some way to do it more efficiently and to instead call something like:

names.removeRange(0, k);


Note that I prefer not to construct a whole new list using
sublist()
, as for small
k
values, popping
k
times would be even more efficient than constructing the new list

Answer

Maybe Something like this :

names.subList(0, k).clear();

this is more efficient but doesn't release memory according to sublist it's just a view:

names.sublist(k, names.size());