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刪除。



猜您在找 java8之list集合中取出某一屬性的方法 java 8 list的stream操作 list中的對象中的某一個成員取出轉為該成員的list,以及對象過濾,篩選某個屬性后的成員 js提取對象數組中的某一個屬性組成新數組 Java8 將List 中某個屬性取出來為單獨的一個集合List Java8 使用 stream().map()提取List對象的某一列值及排重 Java8 使用 stream().map()提取List對象的某一列值及排重 如何根據List中的Object的某一屬性對List進行排序? List中bean某屬性值轉換為list 對list集合中的對象按照對象的某一屬性進行排序 獲取List集合對象中某一列屬性值
 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM