Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda: given a list, remove all elements except for the first element, without creating a new list [duplicate]

Tags:

java

arraylist

I am new to java programming, been programing in php so I'm used to this type of loop:

int size = mapOverlays.size();
for(int n=1;n<size;n++)
{
    mapOverlays.remove(n);
}

So I want to remove everything but the first item, so why doesn't this work? As I get it, after removal, array keys are rearranged or not?

like image 250
dfilkovi Avatar asked Jun 02 '26 09:06

dfilkovi


1 Answers

You could use

mapOverlays.subList(1, mapOverlays.size()).clear();
like image 161
Adam Crume Avatar answered Jun 03 '26 22:06

Adam Crume



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!