Retrieve an array of values assigned to a particul

2019-07-28 23:22发布

问题:

Let's say, I have an array of complex data type objects. For example: FullName[100]. Each FullName object has has 2 class member variables: String FirstName and String LastName. Now, from this array of FullName objects, I want to retrieve an array of String FirstNames[].

How can I do this without the extensive for loop application?

回答1:

You can try to take a look at Functional Programming in Java and apply map function from one of the libraries.



回答2:

I'm not sure why avoiding a loop is so important, but you could do it like this: You could store the names in String arrays and use the Flyweight pattern for your FullName class. So your FullName instances hold a reference to these arrays, and indices that point to the correct elements in the array.



回答3:

In Java 8 you can do something like this:

public class Test {
    class FullName {
        private String firstName;
        String getFirstName(){return firstName;}
    }


    void main(String... argv) {
        FullName names[] = {new FullName()};
        String[] firstNames = Arrays.stream(names).map(FullName::getFirstName).toArray(String[]::new);
    }
}