0

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?

benscabbia
  • 17,592
  • 13
  • 51
  • 62
  • Do you need to return `String[]` or is `List` acceptable? –  Dec 29 '14 at 16:10
  • 1
    possible duplicate of [The easiest way to transform collection to array?](http://stackoverflow.com/questions/3293946/the-easiest-way-to-transform-collection-to-array) –  Dec 29 '14 at 17:22
  • Not a duplicate, it's not just transforming to array, it's transforming to array of a specific property (in this case - id) – haimlit Dec 29 '14 at 18:21

1 Answers1

6
public String[] getAllId() {
    return allPeople.stream().map(Person::getId).toArray(String[]::new);
}
Marcelo Glasberg
  • 29,013
  • 23
  • 109
  • 133
  • 2
    Please note that this answer requires new methods and syntax introduced in Java 8. –  Dec 29 '14 at 16:19