【问题标题】:Java stream, get multiple properties from objectJava流,从对象中获取多个属性
【发布时间】:2021-03-03 12:48:46
【问题描述】:

我有一个这样的对象:

public class Transaction {
    private long buyerId;
    private long sellerId;
... }

给定List<Transaction>,我想要所有参与这些交易的买家/卖家的 ID,例如在Collection<Long>。这是我的工作解决方案:

List<Transaction> transactions = getTransactions();
Stream<Long> buyerIds = transactions.stream().map( Transaction::getBuyerId );
Stream<Long> sellerIds = transactions.stream().map( Transaction::getSellerId );
Collection<Long> allBuyerSellerIds = Stream.concat( buyerIds, sellerIds )
                .collect( Collectors.toList() );

但是,如果我能做到这一点而无需遍历 transactions 两次,那就太好了。我怎样才能做到这一点?即我想用一个流遍历transactions,每次都获取多个属性。

谢谢。

【问题讨论】:

  • 返回 2 个 long 元素的数组
  • 您确定要使用 toList() 而不是 toSet()? List 可能有重复项,而 Set 则不会。
  • 公平点,谢谢@VGR。

标签: java collections java-stream


【解决方案1】:

您可以使用flatMap,因为您最终还是希望它们在一个集合中。

getTransactions().stream()
 .flatMap(t -> Stream.of(t.getBuyerId(), t.getSellerId()))
 .collect(toList());

如果您不希望它们在单个集合中,则最好使用传统循环。

【讨论】:

    猜你喜欢
    • 2018-05-04
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多