Java8 stream filter by several 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 the migration history:

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

But I want to get fromAccountID and toAccountID , so the result will be List of Transfer s. How can I do this using the functions of the Java8 Stream filter?

+5
source share
2 answers

filter by two properties and collect in a list.

 List<Transfer> resultSet = transfers.stream().filter(t -> t.getFromAccountID().equals(id) || t.toAccountID().equals(id)) .collect(Collectors.toList()); 
+2
source

You can filter on two properties ( getFromAccountID() and getToAccountID() ) and collect elements that pass filter to List :

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

Source: https://habr.com/ru/post/1274317/


All Articles