当有一个
List<Person>
时,是否有可能从中得到所有person.getName()
的列表?
是否有准备好的调用,或者我是否必须编写一个 foreach 循环,例如:
List<Person> personList = new ArrayList<Person>();
List<String> namesList = new ArrayList<String>();
for(Person person : personList){
namesList.add(personList.getName());
}
Java 8 及以上版本:
List<String> namesList = personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
在 Java 16+ 中,你可以用
.toList()
结束它
如果您需要确保获得
ArrayList
结果,则必须将最后一行更改为:
...
.collect(Collectors.toCollection(ArrayList::new));
Java 7 及以下版本:
Java 8之前的标准集合API不支持这种转换。你必须编写一个循环(或者将其包装在你自己的一些“映射”函数中),除非你转向一些更高级的集合 API/扩展。
(您的 Java 代码片段中的行正是我将使用的行。)
CollectionUtils.collect
和 Transformer
Lists.transform
方法。
您可能已经这样做了,但对于其他人来说
使用Java 1.8
List<String> namesList = personList.stream().map(p -> p.getName()).collect(Collectors.toList());
试试这个
Collection<String> names = CollectionUtils.collect(personList, TransformerUtils.invokerTransformer("getName"));
使用 apache commons 集合 api。
我认为你永远需要这样做。但如果你总是需要这样的东西,那么我建议创建另一个类,例如将其称为
People
,其中 personList
是一个变量。
类似这样的:
class People{
List<Person> personList;
//Getters and Setters
//Special getters
public List<string> getPeopleNames(){
//implement your method here
}
public List<Long> getPeopleAges(){
//get all people ages here
}
}
在这种情况下,您每次只需要调用一个 getter。
未经测试,但这就是想法:
public static <T, Q> List<T> getAttributeList(List list, Class<? extends Q> clazz, String attribute)
{
List<T> attrList= new ArrayList<T>();
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。使用它不会避免迭代所有项目,但代码会更加压缩。
除了您建议的方法之外,在 Java 中没有其他方法可以做到这一点,至少只要您坚持使用标准的 Java Collection API。
我一直希望有这样的东西......特别是当我尝到了 Ruby 的自由之甜之后,它有一些很棒的东西,比如使用闭包进行收集和选择。