benscabbia
benscabbia

Reputation: 18082

Converting List of objects to an Array of Strings

In my main class, I have: List<Person> allPeople = new ArrayList<>();

Then in the class I have a method which returns a String array of all the Id of people (Person has an accessor method getId() ).

What is the prettiest way to convert the list to an array with just the Ids as String?

This is my current solution:

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

Above works, but is there a 'better' way to do this?

Upvotes: 0

Views: 1977

Answers (1)

Marcelo Glasberg
Marcelo Glasberg

Reputation: 30919

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

Upvotes: 6

Related Questions