Retrieve an array of values assigned to a particular class member from an array of objects in java

孤街浪徒 提交于 2019-12-11 13:14:55

问题


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


来源:https://stackoverflow.com/questions/15473383/retrieve-an-array-of-values-assigned-to-a-particular-class-member-from-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!