获取List中对象的属性列表

如果有一个List ,是否有可能获得所有person.getName() List? 是否有一个准备好的调用,或者我必须写一个foreach循环,如:

 List personList = new ArrayList(); List namesList = new ArrayList(); for(Person person : personList){ namesList.add(personList.getName()); } 

Java 8及以上版本:

 List namesList = personList.stream() .map(Person::getName) .collect(Collectors.toList()); 

如果您需要确保获得ArrayList ,则必须将最后一行更改为:

  ... .collect(Collectors.toCollection(ArrayList::new)); 

Java 7及以下版本:

Java 8之前的标准集合API不支持此类转换。 你必须编写一个循环(或将它包装在你自己的某个“map”函数中),除非你转向一些更高级的集合API /扩展。

(Java片段中的行正好是我要使用的行。)

在Apache Commons中,您可以使用CollectionUtils.collectTransformer

在Guava中,您可以使用Lists.transform方法。

试试这个

 Collection names = CollectionUtils.collect(personList, TransformerUtils.invokerTransformer("getName")); 

使用apache commons collection api。

你可能已经这样做了,但对其他人来说

使用Java 1.8

 List namesList = personList.stream().map(p -> p.getName()).collect(Collectors.toList()); 

我想你总是需要那样做。 但是,如果你总是需要这样的东西,那么我建议创建另一个类,例如将其命名为personList ,其中personList是一个变量。

像这样的东西:

 class People{ List personList; //Getters and Setters //Special getters public List getPeopleNames(){ //implement your method here } public List getPeopleAges(){ //get all people ages here } } 

在这种情况下,您每次只需要调用一个getter。

没有测试,但这是个想法:

 public static  List getAttributeList(List list, Class clazz, String attribute) { List attrList= new ArrayList(); attribute = attribute.charAt(0).toUpperCase() + attribute.substring(1); String methodName = "get"+attribute; for(Object obj: personList){ T aux = (T)clazz.getDeclaredMethod(methodName, new Class[0]).invoke(obj, new Object[0]); attrList.add(aux); } } 

看看http://code.google.com/p/lambdaj/ – 有一个与Java相当的LINQ。 使用它不会避免迭代所有项目,但代码将更加压缩。

您将不得不遍历并访问每个对象getName()

也许番石榴可以做一些奇特的事……

在Java中没有其他方法可以做到这一点,至少只要你坚持使用标准的Java Collection API。

我一直希望这样的东西很长一段时间……特别是因为我尝到了Ruby的甜蜜自由,它有很棒的东西,如收集和选择使用闭合。