[英]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.