Java 流,从对象中获取多个属性
Java stream, get multiple properties from object
我有一个这样的对象:
public class Transaction {
private long buyerId;
private long sellerId;
... }
给定一个 List<Transaction>
,我想要这些交易中涉及的所有 buyers/sellers 的 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
,每次都获得多个属性。
谢谢。
您可以使用 flatMap
,因为无论如何您最终都希望它们在一个集合中。
getTransactions().stream()
.flatMap(t -> Stream.of(t.getBuyerId(), t.getSellerId()))
.collect(toList());
如果您不想将它们放在一个集合中,则最好使用传统循环。
我有一个这样的对象:
public class Transaction {
private long buyerId;
private long sellerId;
... }
给定一个 List<Transaction>
,我想要这些交易中涉及的所有 buyers/sellers 的 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
,每次都获得多个属性。
谢谢。
您可以使用 flatMap
,因为无论如何您最终都希望它们在一个集合中。
getTransactions().stream()
.flatMap(t -> Stream.of(t.getBuyerId(), t.getSellerId()))
.collect(toList());
如果您不想将它们放在一个集合中,则最好使用传统循环。