Convert a list of objects to a list of Long

Viewed 3170

I Have a class as following:

Class1 {
    private Class2 class2;
    ...
}

I want to convert a list of Class1 to a list of Class2::getId(), this is what I tried :

List<Class2> class2List = class1List.stream().map(Class1::getClass2).collect(Collectors.toList());
List<Long> class2Ids = class2List .stream().map(Class2::getId).collect(Collectors.toList());

Isn't there a way to do this in a single instruction ?

1 Answers

You can chain as many intermediate operations as you please...

class1List.stream()
          .map(Class1::getClass2)
          .map(Class2::getId)
          .collect(Collectors.toList());
Related