1

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?

Bikash Gyawali
  • 969
  • 2
  • 15
  • 33
  • 3
    Basically: no, you can't... There will always be a loop iterating through the array somehow. Maybe you won't see it, as some library hides it behind some clever function calls, but it will be there... – ppeterka Mar 18 '13 at 09:33

3 Answers3

1

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

Community
  • 1
  • 1
denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
0

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.

erikd
  • 11
  • 3
0

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