2013-12-03 31 views
1

可以说我有一个对象用户的ArrayList,所以ArrayList<user>。用户对象有一个属性userIDArrayList获取对象属性的所有值

而不是迭代列表我自己和添加userIDs到一个单独的列表中,是否有API调用,我可以通过它的属性我想要的对象,并有一个这些属性的列表返回给我?看看API,没有什么突出的。

在Java 7或<中寻找解决方案。

回答

0

这听起来像你想使用Map

地图使用Key, Value对。您可以将userID作为关键字,将实际的user对象指定为值。

You can read more here

+0

确实,唯一的问题是该对象是使用Jackson从json映射而来,所以希望能够让代码更简单一些。 – Michael

+0

比散列图更简单吗?我不确定你期待的是什么。这很容易实现。 – redFIVE

+0

我认为你错过了这一点。杰克逊很容易解析清单。解析为一个Map会增加代码的复杂性。 – Michael

4

你可以做到这一点使用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] 

片段here


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

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] 
+0

有趣的是,不幸的是我们没有运行8,但很高兴知道这是即将到来的。对于Java 7或< – Michael

+0

@Michael号的任何解决方案。但是,你是否想要构建一个可以返回一个字段列表的方法?类似'List get(List l,String fieldName)'? –

+0

@Michael我使用反射添加了一个解决方案。你可以得到你想要的所有用户的属性列表,你只需要提供你想要收集数据的字段的正确名称。请注意,我不是这个解决方案的粉丝。 –

1

您可以使用番石榴的Collections2#transform方法有同样的结果。

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

番石榴支持Java 7和较低的,所以如果你想使用一个外部库,上面会工作你的情况。

不幸的是,你将不得不为其他任何对象及其内部字段执行类似的逻辑。它不像反射一样是一个通用的解决方案,它只是一个更紧凑的解决方案。

+0

不错的罕见解决方案...感谢这个技巧! –