2014-12-28 25 views
0

的數組在我的主類,我有:List<Person> allPeople = new ArrayList<>();轉換對象的列表,以字符串

然後在課堂上我有一個返回所有的人Id(人的String數組的方法具有的存取方法getId())。

什麼是最簡單的方式將列表轉換爲只有ID爲String的數組?

這是我目前的解決方案:

public String[] getAllId() { 

    Object[] allPeopleArray = allPeople.toArray(); 
    String allId[] = new String[allPeople.size()];    

    for(int i=0; i<=allPeople.size()-1; i++){ 
     allId[i] = ((Person)allPeopleArray [i]).getId();      
    } 

    return allId; 
} 

上述工作,但有一個「好」的方式來做到這一點?

+0

你需要返回'String []'還是'List '可以接受嗎? –

+1

[將集合轉換爲數組的最簡單方法]的可能重複(http://stackoverflow.com/questions/3293946/the-easiest-way-to-transform-collection-to-array) –

+0

不是重複的,它是不只是轉換爲數組,它正在轉換爲一個特定屬性的數組(在這種情況下是 - id) – haimlit

回答

5
public String[] getAllId() { 
    return allPeople.stream().map(Person::getId).toArray(String[]::new); 
} 
+2

請注意,此答案需要Java 8中引入的新方法和語法。 –