You can use 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;
}
}
Exit:
[Bob, Alice]
Demo is here .
<h / "> In addition, you can define a method that will accept your list as a parameter and a function that 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());
List<Integer> lAges = processElements(people, p -> p.getAge());
, Collectors ():
Map<Integer, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));