![](/img/trans.png)
[英]How to get a map object, from a list object which contains multiple different mysql dates using java stream
[英]Java stream, get multiple properties from object
我有一個像這樣的 object:
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
兩次的情況下做到這一點,那就太好了。 我怎樣才能做到這一點? 即我想用 stream 遍歷transactions
,並且每次都獲得多個屬性。
謝謝。
您可以使用flatMap
,因為您最終還是希望它們在一個集合中。
getTransactions().stream()
.flatMap(t -> Stream.of(t.getBuyerId(), t.getSellerId()))
.collect(toList());
如果您不希望它們在單個集合中,則最好使用傳統的循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.