How to make a new list with a property of an object which is in another list

Javatar picture Javatar · Jun 11, 2012 · Viewed 79k times · Source

Imagine that I have a list of certain objects:

List<Student>

And I need to generate another list including the ids of Students in the above list:

List<Integer>

Avoiding using a loop, is it possible to achieve this by using apache collections or guava?

Which methods should be useful for my case?

Answer

Kaushik picture Kaushik · May 8, 2015

Java 8 way of doing it:-

List<Integer> idList = students.stream().map(Student::getId).collect(Collectors.toList());