K--
K--

Reputation: 734

Java stream, get multiple properties from object

I have an object like this:

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

Given a List<Transaction>, I want the ids of all the buyers/sellers involved in those transactions, e.g. in a Collection<Long>. This is my working solution:

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

However, it would be nice if I could do this without iterating through transactions twice. How can I do this? i.e. I want to iterate through transactions with a stream, and get multiple properties each time.

Thanks.

Upvotes: 1

Views: 2055

Answers (1)

daniu
daniu

Reputation: 14999

You can use flatMap since you want them in one collection in the end anyway.

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

If you didn't want them in a single collection, you might be better off with a conventional loop instead.

Upvotes: 4

Related Questions