Reputation: 359
I would love to do this in one line:
ArrayList<Integer> newArray = new ArrayList<>(oldArray);
newArray.remove(0);
function(newArray);
I have tried this:
function(new ArrayList<>(oldArray.remove(0));
But it does not work. Is it possible? Any suggestion?
Upvotes: 1
Views: 182
Reputation: 4643
In java 8 you can do this:
function(oldArray.stream().skip(1).collect(Collectors.toList()));
If you need an ArrayList
use this:
function(oldArray.stream().skip(1).collect(Collectors.toCollection(ArrayList::new)));
Upvotes: 1
Reputation: 131456
To program by interface that is a good practice favor List
over ArrayList
as parameter of your function()
method.
You could so do it :
function(oldArray.stream().skip(1).collect(toList());
If you really need to use a specific List
implementation you can still do :
function(oldArray.stream().skip(1).collect(toCollection(ArrayList::new));
Upvotes: 1
Reputation: 45329
The simplest way is to use subList
:
function(new ArrayList<>(oldArray.subList(1, oldArray.size())));
That will create a new ArrayList
initialized with all elements in oldArray
except the first one.
Upvotes: 3