1

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.

3
  • return array of 2 long elements Commented Mar 3, 2021 at 12:51
  • 1
    Are you sure you want toList() rather than toSet()? A List may have duplicates, while a Set will not. Commented Mar 3, 2021 at 19:26
  • Fair point, thanks @VGR. Commented Mar 4, 2021 at 13:32

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.