使用Java 8 Stream获取嵌套属性(nested property)的属性数组。

4

基于这个问题...

我有这段代码:

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

如何以简单的方式做到这一点?
1个回答

4

你的方法相对来说不太高效,可以将方法链式调用:

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

这种方法更好的原因:

  • 易于理解正在发生的事情

  • 效率更高,因为不需要急切地在每个中间步骤创建新的集合对象。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接