简体   繁体   中英

Java8 stream filter by multiple parameters

I have the following class:

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

and a List of Transfer s:

....
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 Transfer s. How can I do that with Java8 Stream filter functions?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM