只是好奇...更好的方式复制/克隆ArrayList的一部分?(just curious … better way copy/clone part of an ArrayList?)

复制部分ArrayList比我正在做的更有效/更快/更敏感吗?

public ArrayList<FooObject> getListOfFlagged() { for(FooObject fooObject: foos) { //for each item in the original array, where the item isFlagged... if(fooObject.isFlagged) { someOtherArray.add(fooObject); } } return someOtherArray; }

Is there a more efficient/quicker/more sensible to copy part of an ArrayList than the way I'm doing it?

public ArrayList<FooObject> getListOfFlagged() { for(FooObject fooObject: foos) { //for each item in the original array, where the item isFlagged... if(fooObject.isFlagged) { someOtherArray.add(fooObject); } } return someOtherArray; }

最满意答案

您可以使用guava Collections2.filter()方法。 它看起来更具功能性:

Collections2.filter(foos, new Predicate<FooObject>() { @Override public boolean apply(FooObject input) { return fooObject.isFlagged(); } })

结果由原始foos集合支持,因此如果您需要副本,则必须使用new ArrayList<FooObject>(filteredCollection)制作防御性副本。

You can use Collections2.filter() method from guava. It'll look more functionally:

Collections2.filter(foos, new Predicate<FooObject>() { @Override public boolean apply(FooObject input) { return fooObject.isFlagged(); } })

The result is backed by your original foos collection, so if you need a copy, then you have to make a defensive copy with new ArrayList<FooObject>(filteredCollection).

更多推荐