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?

3
  • Do you need to return String[] or is List<String> acceptable? Commented Dec 29, 2014 at 16:10
  • 1
    possible duplicate of The easiest way to transform collection to array? Commented Dec 29, 2014 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) Commented Dec 29, 2014 at 18:21

1 Answer 1

6
public String[] getAllId() {
    return allPeople.stream().map(Person::getId).toArray(String[]::new);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that this answer requires new methods and syntax introduced in Java 8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.