If you don't want to iterate over List<Persons> people you could create a view on the list, which will show a Person in a specific way.
public class ListView<L, T> extends AbstractList<T> {
private List<L> original;
private Mapper<L, T> mapper;
private ListView(List<L> original, Mapper<L, T> mapper) {
this.original = original;
this.mapper = mapper;
}
@Override
public T get(int index) {
return mapper.map(original.get(index));
}
@Override
public int size() {
return original.size();
}
private static <L, T> ListView<L, T> of(List<L> original, Mapper<L, T> mapper) {
return new ListView<>(original, mapper);
}
}
A Mapper is an interface and defines how we want to view a Person.
private static abstract interface Mapper<I, O> {
O map(I input);
}
Now we can use this to implement getNames:
public List<String> getNames(ArrayList<Person> people) {
return ListView.of(people, new Mapper<Person, String>() {
@Override
public String map(Person person) {
return person.getName();
}
});
}
Applied to an example:
ArrayList<Person> people = new ArrayList<>(Arrays.asList(new Person("Micky", "1"), new Person("Donald", "2"), new Person("Daisy", "3")));
List<String> names = getNames(people);
System.out.println(names); // [Micky, Donald, Daisy]
Please note: The shown implementation of ListView does not support modification. Thus it's a read only List. If you don't want to add a name without adding a Person then this implementation should be sufficient.
Using Java 8 would result in much simpler code. But you said you cannot. Thus this approach without Java 8 features.
List<Stringto be returned?