ArrayList获取对象属性的所有值 [英] ArrayList get all values for an object property

查看:643
本文介绍了ArrayList获取对象属性的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个对象User的ArrayList,所以ArrayList<user>.用户对象具有属性userID.

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

不是我自己遍历列表并将用户ID添加到单独的列表中,而是在API调用中,我可以在该对象上传递我想要的属性,并向我返回这些属性的列表?通过API进行了浏览,没有发现任何异常.

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.

正在寻找Java 7或<中的解决方案.

Looking for a solution in Java 7 or <.

推荐答案

您可以使用 lambdas表达式(Java 8):

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;
  }
}

输出:

[1, 2, 3, 4]

摘录 此处 .


使用反射的最丑陋的解决方案:


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;
      }
}

输出:

[1, 2, 3, 4]

这篇关于ArrayList获取对象属性的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆