使用流Java 8获取属性数组、属性数组(嵌套属性)
基于此 我有以下代码:使用流Java 8获取属性数组、属性数组(嵌套属性),java,java-8,java-stream,Java,Java 8,Java Stream,基于此 我有以下代码: 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]
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]);
List id=collectionEntityDTO.stream().map(EntityDTO::getId).collect(Collectors.toList());
列表代码=ids.stream().map(IdDTO::getCode).collect(Collectors.toList());
Long[]arrayCodes=code.toArray(新的Long[0]);
如何以这种简单的方式做到这一点?您的方法效率很低,只需将这些方法链接起来:
collectionEntityDTO.stream()
.map(EntityDTO::getId)
.map(IdDTO::getCode)
.toArray(Long[]::new);
这种方法更好,因为:
- 阅读正在发生的事情更容易
- 如前所述,它的效率更高,不需要急切地 在每个中间步骤创建新的集合对象
- 垃圾变量不会造成混乱
- 更容易并行化