10

I have the following class:

public class Transfer {
    private String fromAccountID;
    private String toAccountID;
    private double amount;
}

and a List of Transfers:

....
private List<Transfer> transfers = new ArrayList<>();

I know how to get one transfer history:

transfers.stream().filter(transfer -> 
    transfer.getFromAccountID().equals(id)).findFirst().get();

But I want to get by fromAccountID and toAccountID, so the result will be a List of Transfers. How can I do that with Java8 Stream filter functions?

2
  • 2
    you should never call get() straight from an optional result except in cases where you know there will be a value present. rather you should utilise orElse or orElseGet depending on which is most appropriate for your case Commented Dec 25, 2017 at 19:36
  • your advise was really helpful today, get() threw an exception, in order to handle it, I've used orElse and check it if it is null. Cheers! Commented Dec 26, 2017 at 18:53

2 Answers 2

7

filter by the two properties and collect into a list.

List<Transfer> resultSet = 
      transfers.stream().filter(t -> id.equals(t.getFromAccountID()) || 
                        id.equals(t.toAccountID()))
               .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

5

You can filter by both properties (getFromAccountID() and getToAccountID()), and collect the elements that pass the filter to a List:

List<Transfer> filtered = 
    transfers.stream()
             .filter(t -> t.getFromAccountID().equals(id) || t.getToAccountID().equals(id))
             .collect(Collectors.toList());

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.