Say I have an list of objects with two fields field1
and field2
, both of String type.
How do I get a list of all field1
values wit
Ancient question, but I came upon it while looking to see if I could improve on a similar solution.
You can implement the List
interface without creating a fleshed-out ArrayList
, and thus not iterating over the parent object.
final List entities = getEntities()
final List field1 = new AbstractList() {
public String get(int index) {
return entities.get(index).getField1();
}
public int size() {
return entities.size();
}
}
That gives you a List without iterating over the parent object.
Random access to the derived List
will be as expensive as random access to the underlying List
; if you're using an implementation of List
that does not provide quick random access, you might have to jump through a couple of hoops (i.e. implementing more methods of List
. But this should work for 99% of the cases where you need a light-weight adapter.