您可以将 Java 8 与 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;
}
}
输出:
[Bob, Alice]
演示here.
或者,您可以定义一个方法,将您的列表作为参数,以及您要为该列表的每个元素应用的函数:
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;
}
那就做吧:
List<String> lNames = processElements(people, p -> p.getName()); //for the names
List<Integer> lAges = processElements(people, p -> p.getAge()); //for the ages
//etc.
如果您想按年龄分组,Collectors 类提供了不错的实用程序(示例):
Map<Integer, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));