基于此Question ...
我有这个代码:
List<IdDTO> ids = collectionEntityDTO.stream().map(EntityDTO::getId).collect(Collectors.toList());
List<Long> codes = ids.stream().map(IdDTO::getCode).collect(Collectors.toList());
Long[] arrayCodes = codes.toArray(new Long[0]);
如何以这种简单的方式做到这一点?
最佳答案
您的方法效率很低,只需链接方法:
collectionEntityDTO.stream()
.map(EntityDTO::getId)
.map(IdDTO::getCode)
.toArray(Long[]::new);
这种方法更好,因为:
更容易阅读正在发生的事情
如前所述,它更高效,因为不需要急切 在每个中间步骤创建新的集合对象。
- 垃圾变量不会造成困惑。
- 更容易并行化。
关于java - 使用流 Java 8 获取属性数组、属性数组(嵌套属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53733215/