【问题标题】:Get Array of Property, of Property (nested property) using stream Java 8使用流 Java 8 获取属性数组,属性(嵌套属性)
【发布时间】:2019-05-12 23:30:04
【问题描述】:

基于此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]);

如何以这种简单的方式做到这一点?

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    你的方法效率很低,只是链接方法:

    collectionEntityDTO.stream()
            .map(EntityDTO::getId)
            .map(IdDTO::getCode)
            .toArray(Long[]::new);
    

    这种方法更好,因为:

    • 更容易阅读正在发生的事情

    • 正如已经提到的那样,它更高效,因为不需要急切 在每个中间步骤创建新的集合对象。

    • 垃圾变量没有混乱。
    • 更容易并行化。

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2018-07-31
      相关资源
      最近更新 更多