Retrieve an array of values assigned to a particul

2019-07-28 22:50发布

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?

3条回答
够拽才男人
2楼-- · 2019-07-28 23:05

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

查看更多
冷血范
3楼-- · 2019-07-28 23:06

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);
    }
}
查看更多
聊天终结者
4楼-- · 2019-07-28 23:08

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.

查看更多
登录 后发表回答