Search code examples
javalistcollectionsjava-streamguava

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


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?


Solution

  • Java 8 way of doing it:-

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