You can using Java 8 with lambda expressions :
List<String> listNames = people.stream().map(u -> u.getName()).collect(Collectors.toList());
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Test {
public static void main(String args[]){
List<Person> people = Arrays.asList(new Person("Bob",25,"Geneva"),new Person("Alice",27,"Paris"));
List<String> listNames = people.stream().map(u -> u.getName()).collect(Collectors.toList());
System.out.println(listNames);
}
}
class Person
{
private String name;
private int age;
private String location;
public Person(String name, int age, String location){
this.name = name;
this.age = age;
this.location = location;
}
public String getName(){
return this.name;
}
}
Output :
[Bob, Alice]
Demo here.
Alternatively, you can define a method that will take your list as parameter and the function you want to apply for each element of this list :
public static <X, Y> List<Y> processElements(Iterable<X> source, Function <X, Y> mapper) {
List<Y> l = new ArrayList<>();
for (X p : source)
l.add(mapper.apply(p));
return l;
}
Then just do :
List<String> lNames = processElements(people, p -> p.getName()); //for the names
List<Integer> lAges = processElements(people, p -> p.getAge()); //for the ages
//etc.
If you want to group people by age, the Collectors
class provide nice utilities (example):
Map<Integer, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));