创建一个新的ArrayList,其中包含除一行代码中的一个元素外的其他ArrayList的所有元素



我很想在一行中做到这一点:

ArrayList<Integer> newArray = new ArrayList<>(oldArray);
newArray.remove(0);
function(newArray);

我试过这个:

function(new ArrayList<>(oldArray.remove(0));

但它不起作用。有可能吗?有什么建议吗?

最简单的方法是使用subList:

function(new ArrayList<>(oldArray.subList(1, oldArray.size())));

这将创建一个新的CCD_ 2,该CCD_。

通过接口编程,这是一种很好的做法,更喜欢List而不是ArrayList作为function()方法的参数。

你可以这么做:

function(oldArray.stream().skip(1).collect(toList());

如果你真的需要使用特定的List实现,你仍然可以:

function(oldArray.stream().skip(1).collect(toCollection(ArrayList::new));

在java 8中,您可以执行以下操作:

function(oldArray.stream().skip(1).collect(Collectors.toList()));

如果您需要ArrayList,请使用以下内容:

function(oldArray.stream().skip(1).collect(Collectors.toCollection(ArrayList::new)));

最新更新