Is there an equivalent of Javascript's Array.map in Java 8?

Viewed 8419

Is there an equivalent of Javascript's Array.map in Java?

I have been playing with Java 8 :

List<Long> roleList = siteServiceList.stream()
        .map(s -> s.getRoleIdList()).collect(Collectors.toList());

but this doesn't work I don't know why the warning says Incompatible Type.

How can I do this in Java8?

1 Answers

If roleIdList is a List<Long> and you want to get a List<Long> you have to use flatMap instead :

List<Long> roleList = siteServiceList.stream()
                .flatMap(s -> s.getRoleIdList().stream())
                .collect(Collectors.toList());

If you insist using map the return type should be List<List<Long>> :

List<List<Long>> roleList = siteServiceList.stream()
    .map(MyObject::getRoleIdList)
    .collect(Collectors.toList());
Related