How to get a list of specific fields values from objects stored in a list?

后端 未结 12 1053
长发绾君心
长发绾君心 2021-01-31 08:23

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

12条回答
  •  别那么骄傲
    2021-01-31 08:52

    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.

提交回复
热议问题