簡體   English   中英

如何使用 java stream 將一些 class 的列表轉換為 ZA2F2ED4F8EBC26BABC4C4C4F2ED4F8EBC26BABC1 的任何一個屬性的列表/集

[英]How to use java stream to convert a List of some class to a list/set of any one property of class?

我有一個 class

class Student{  
int id; 
 String name;   
 public static void main(String args[]){   
  Student s1=new Student();
  System.out.println(s1.id); 
  System.out.println(s1.name);  
 }  
} 

我有一個 class 學生的列表,說, List<Student> students的大小為 100。

I want to stream id of all the students and save it in a set Set<int>id , one easy way to do it is using a for loop, can someone please tell how the same can be implemented using java stream API.

List<Student> students = /* ... */;
Set<Integer> studentIds = students.stream()
        .map(s -> s.id)
        .collect(Collectors.toSet());

如果您的學生 object 有 ID 的 getter 方法,您可以直接引用該方法

public class Student {
  private int id;
  public int getId() {
    return this.id;
  }
}

Set<Integer> studentIds = students.stream()
        .map(Student::getId) // <-
        .collect(Collectors.toSet());

注意:注意:原始數據類型( int )不能用作泛型參數,所以必須使用包裝類 => Set<Integer>而不是Set<int>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM