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

Dimitri Kopriwa :

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?

YCF_L :

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());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460199&siteId=1