ArrayList get all values for an object property

六眼飞鱼酱① 提交于 2019-12-24 12:36:15

问题


Lets say I have an ArrayList of a object User so ArrayList<user>. A User object has a property userID.

Rather than iterating the list myself and adding userIDs to a separate list, is there and API call where I could pass it the property I want on that object and have a list of these properties returned to me? Had a look through the API and nothing stood out.

Looking for a solution in Java 7 or <.


回答1:


You can do this using lambdas expressions (Java 8) :

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Test {
  public static void main(String args[]){
    List<User> users = Arrays.asList(new User(1,"Alice"), new User(2,"Bob"), new User(3,"Charlie"), new User(4,"Dave"));
    List<Long> listUsersId = users.stream()
                                  .map(u -> u.id)
                                  .collect(Collectors.toList());
    System.out.println(listUsersId);
  }
}

class User {
  public long id;
  public String name;

  public User(long id, String name){
    this.id = id;
    this.name = name;
  }
}

Output :

[1, 2, 3, 4]

Snippet here.


Ugliest solution using reflection :
public class Test {
    public static void main (String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
         List<User> users = Arrays.asList(new User(1,"Alice"), new User(2,"Bob"), new User(3,"Charlie"), new User(4,"Dave"));
         List<Object> list = get(users,"id");
         System.out.println(list);
    }

    public static List<Object> get(List<User> l, String fieldName) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
        Field field = User.class.getDeclaredField(fieldName);
        field.setAccessible(true);
        List<Object> list = new ArrayList<>();
        for(User u : l){
            list.add(field.get(u));
        }
        field.setAccessible(false);
        return list;
    }
}
class User {
      private long id;
      private String name;

      public User(long id, String name){
        this.id = id;
        this.name = name;
      }
}

Output :

[1, 2, 3, 4]



回答2:


You can use Guava's Collections2#transform method to have the same result.

List<Integer> userIDs = Collections2.transform(users, new Function<User, Integer> (){
                            public Integer apply(User user) {
                                   return user.getUserID();
                            }
                        });

Guava supports Java 7 and lower, so if you want to use an external library, the above will work in your case.

Unfortunately, you will have to do similar logic for any other objects and their inner fields you might have. It's not as a generic solution as the reflection one, it's just a more compact one.




回答3:


It sounds like you want to use a Map.

Maps use a Key, Value pair. You can assign the userID as the key and the actual user object as the value.

You can read more here



来源:https://stackoverflow.com/questions/20358510/arraylist-get-all-values-for-an-object-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!