lambda 表示式從集合中獲取某個欄位屬性的集合

pyd1040201698發表於2020-11-26

 

@Data
public class SchoolBoy {
	private String girlId;
	
	private String id;
	
	private String name;
 
	private String grilName;
}
public class Test3 {

    public static void main(String[] args) {
        List<SchoolBoy> schoolBoys = new ArrayList<>();
        SchoolBoy boy1 = new SchoolBoy();
        boy1.setGirlId("1");
        boy1.setId("10");
        boy1.setName("小明");

        SchoolBoy boy2 = new SchoolBoy();
        boy2.setGirlId("2");
        boy2.setId("11");
        boy2.setName("小豪");

        SchoolBoy boy3 = new SchoolBoy();
        boy3.setGirlId("3");
        boy3.setId("12");
        boy3.setName("小白");
        schoolBoys.add(boy1);
        schoolBoys.add(boy2);
        schoolBoys.add(boy3);

        List<String> ids = schoolBoys.stream().map(schoolBoy -> schoolBoy.getId()).collect(Collectors.toList());
        System.out.println(ids);

        List<String> ids2 = schoolBoys.stream().map(SchoolBoy::getId).collect(Collectors.toList());
        System.out.println(ids2);

    }
}

 

相關文章