[Java]基于Stream从对象List中获取对象属性的List

package com.javademo;

public class Person {

    private String name;

    public Person(String name) {
        this.name=name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.javademo;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        //构造包含Person对象的List集合
        List persons=new ArrayList<>();
        persons.add(new Person("Tom"));
        persons.add(new Person("Bob"));
        persons.add(new Person("Jack"));
        //从Person对象的List集合中获取对象属性的List集合
        List names=persons.stream().map(Person::getName).collect(Collectors.toList());
        //打印属性集合
        System.out.println(names);
    }
}

你可能感兴趣的:(代码片段,java)