使用Stream 流提取集合的某个属性

import lombok.Data;

@Data
public class Person {
    public Person() {}
    public Person(String name, Boolean gender, Integer age, float score) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.score = score;
    }
    public Person(String name, Boolean gender) {
        this.name = name;
        this.gender = gender;
    }
    private String name;
    private Boolean gender;
    private Integer age;
    private float score;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender=" + gender +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
import java.util.*;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class StreamDeduplicationTest {
    public static void main(String[] args) {
        Person p1 = new Person("zhangsan",false,19,60);
        Person p2 = new Person("lisi",true,20,80);
        Person p3 = new Person("wangmazi",false,28,70);
        Person p4 = new Person("meiyoule",true,15,50);
        Person p5 = new Person("evsd",true);
        Person p6 = new Person("evsd",true);

        List<Person> personList = Arrays.asList(p1,p2,p3,p4,p5,p6);
        List<String> nameList = personList.stream().map(Person::getName).collect(Collectors.toList());
       
        nameList.forEach(System.out::println);
    }
}
posted @ 2020-12-25 19:58  vwa  阅读(12304)  评论(0编辑  收藏  举报