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?
You can try to take a look at Functional Programming in Java and apply map
function from one of the libraries.
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.
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);
}
}