I have a class
JavaScript
x
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);
}
}
I have a list of class student say, List<Student> students
whose size is 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.
Advertisement
Answer
JavaScript
List<Student> students = /* ... */;
Set<Integer> studentIds = students.stream()
.map(s -> s.id)
.collect(Collectors.toSet());
And if your Students object has a getter method for the ID, you can directly reference the method:
JavaScript
public class Student {
private int id;
public int getId() {
return this.id;
}
}
Set<Integer> studentIds = students.stream()
.map(Student::getId) // <-
.collect(Collectors.toSet());
Note: Note: primitive data types (int
) cannot be used as generic parameters, so you must use wrapper classes.
=> Set<Integer>
instead of Set<int>