简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM