juan fran
juan fran

Reputation: 359

Create a new ArrayList with all the elements of another ArrayList except one in one line of code

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

Answers (3)

Mohsen
Mohsen

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

davidxxx
davidxxx

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

ernest_k
ernest_k

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

Related Questions