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

JavaScript

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

And if your Students object has a getter method for the ID, you can directly reference the method:

JavaScript

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