Java中是否有类似于Javascript的Array.map
的等效方法?
我一直在研究Java 8:
List<Long> roleList = siteServiceList.stream()
.map(s -> s.getRoleIdList()).collect(Collectors.toList());
但是这并不起作用,我不知道为什么警告会说 类型不兼容
。
在Java8中我该怎么做?
roleIdList
是一个 List<Long>
,并且您想获取一个 List<Long>
,则必须使用 flatMap
:List<Long> roleList = siteServiceList.stream()
.flatMap(s -> s.getRoleIdList().stream())
.collect(Collectors.toList());
如果坚持使用map
,返回类型应为List<List<Long>>
:
List<List<Long>> roleList = siteServiceList.stream()
.map(MyObject::getRoleIdList)
.collect(Collectors.toList());
List<List<Long>>
吗? - Andy Turner