当存在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());
}
发布于 2014-11-04 06:21:14
要不是为了别人,你可能已经这么做了。
使用Java 1.8
List<String> namesList = personList.stream().map(p -> p.getName()).collect(Collectors.toList());
发布于 2013-11-23 02:25:17
尝尝这个
Collection<String> names = CollectionUtils.collect(personList, TransformerUtils.invokerTransformer("getName"));
使用apache commons集合api。
发布于 2011-09-05 22:16:46
我认为你总是需要这样做。但是如果您总是需要这样的东西,那么我建议创建另一个类,例如,将其命名为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。
https://stackoverflow.com/questions/7309259
复制相似问题