Java8从对象列表中取出某个属性的列表

List<属性值类型> 属性List = 对象List.stream().map(对象::get方法()).collect(Collectors.toList());

例如:

List<Integer> idList = list.stream().map(User::getId).collect(Collectors.toList());

//或者
List<Integer> idList = list.stream().map(u -> u.getId()).collect(Collectors.toList());

举例

public class HelloWorld {

    public static void main(String[] args) {
List<User> list = new ArrayList<>();
for(int i=1;i<=10;i++) {
User u = new User(i, "用户-" + i);
list.add(u);
}
//取出id列表
//List<Integer> idList = list.stream().map(User::getId).collect(Collectors.toList());
List<Integer> idList = list.stream().map(u -> u.getId()).collect(Collectors.toList()); System.out.println("id列表:" + idList);
}
private static class User{
int id;
String name; public User(int id, String name) {
this.id = id;
this.name = name;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
} }

执行后:

Java8从对象列表中取出某个属性的列表

上一篇:[UE4]VR角色形象:Lock to Hmd、Use Pawn Control Rotation


下一篇:BZOJ3435[Wc2014]紫荆花之恋——动态点分治(替罪羊式点分树套替罪羊树)