2011-09-05 102 views
19

當存在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()); 
} 

回答

48

的Java 8.0及以上:

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

如果你需要確保你得到一個ArrayList結果,你必須在最後一行改爲:

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

Java 7及更低版本:

Java 8之前的標準集合API不支持這種轉換。你必須編寫一個循環(或者將它包裝在你自己的某個「映射」函數中),除非你轉向一些更好的收集API /擴展。

(在Java代碼段的線是完全相同我會用線。)

在Apache中共享,你可以使用CollectionUtils.collectTransformer

番石榴,您可以使用Lists.transform方法。

0

您將不得不遍歷並訪問每個對象getName()

也許guava可以做一些花哨的......

+0

別人

你能提供與番石榴的例子嗎? – Sonnenhut

0

有沒有其他辦法,你用標準的Java API集合堅持做到這一點在Java中比你建議的一個,至少長。

我一直希望有這樣的事情很長一段時間......特別是因爲我嚐到了Ruby的甜美自由,它擁有像收集和選擇封閉工作的美好事物。

1

請看http://code.google.com/p/lambdaj/ - 有LINQ相當於Java。使用它不會避免迭代所有項目,但代碼會更加壓縮。

+1

我不知道這是否會包含在Java 8中。 –

2

我認爲你總是需要這樣做。但是如果你總是需要這樣的事情,那麼我會建議再做一個班,例如把它叫做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 
    } 
} 

在這種情況下,你將只需要在每次調用一個吸氣。

2

未經測試,但這個想法:

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

試試這個

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

使用Apache公地集合API。

6

你可能已經做到了這一點,但使用Java 1.8

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