Search code examples
javaarrayscollectionssub-array

Generate array from existing object's attribute


Let's consider we have this class:

public class Person
{
    public String name;
    public String lastname;
}

Suppose we have collection for that Person class. How can I generate a new String collection which contains just lastnames?

We can do that easily by iterating, but I'm looking for the most efficient way to do this.

Due to some dependencies I can't use Java 8.


Solution

  • Use a for loop and initialize your target collection with the right size:

    String[] lastnames = new String[persons.size()]; // or new ArrayList(persons.size()), ...
    for(int i=0;i<persons.size();i++){
        lastnames[i] = persons.get(i).getLastName();
    }
    

    This would be efficient (O(n)) if direct access is possible in both collections (persons and lastnames).