java 提取出List的某一属性组成list (java 8及以上版本 )


使用java 8 及以上版本

提取list bean中某一属性组成list

 

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.stream.Collectors;
 4 
 5 /**
 6  * @ClassName: ListBeanTest
 7  * @Desc: 使用java 8 提取出list中bean的某一属性组成list
 8  * @author: hatebugs
 9  * @date: 2021年12月11日 下午1:51:16
10  */
11 public class ListBeanTest {
12 
13     public static void main(String[] args) {
14         List<Student> stuList = new ArrayList<Student>();
15         Student st1 = new Student("101", "AAAA");
16         Student st2 = new Student("102", "BBBB");
17         Student st3 = new Student("103", "CCCC");
18         Student st4 = new Student("102", "DDDD");
19         stuList.add(st1);
20         stuList.add(st2);
21         stuList.add(st3);
22         stuList.add(st4);
23         // 1.提取出list对象中的一个属性
24         List<String> stIdList1 = stuList.stream().map(Student::getId).collect(Collectors.toList());
25         stIdList1.forEach(s -> System.out.print(s + " "));
26         System.out.println();
27         System.out.println("----------");
28 
29         // 2.提取出list对象中的一个属性并去重
30         List<String> stIdList2 = stuList.stream().map(Student::getId).distinct().collect(Collectors.toList());
31         stIdList2.forEach(s -> System.out.print(s + " "));
32     }
33 
34 }
35 /**
36  * 输出结果:
37  * 
38  * 101 102 103 102 ---------- 101 102 103
39  * 
40  **/
public class Student {
    
    private String id;
    private String lastname;
    

    public Student(String id, String lastname) {
        super();
        this.id = id;
        this.lastname = lastname;
    }
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

 

 

参考自: https://blog.csdn.net/nightliar/article/details/78657949

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM