Skip to content
Advertisement

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

I have a 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);  
 }  
} 

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

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:

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>

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement