class Transaction
{
int transactionId,transactionType,transactionStatus;
double transactionAmount;
Date transactionDate;
}
我想使用RxJava基于 Transaction 组合来过滤交易列表。组合更改运行时,以便有人可以帮助我如何使用 filter()运算符来实现相同的
答案 0 :(得分:2)
前段时间我不得不做你想做的事情。我创建了一个简单的解决方案来处理多重过滤,如下所示:
public class ExampleUnitTest {
@Test
public void testSample() throws Exception {
TransactionDatabase transactionDatabase = new TransactionDatabase();
transactionDatabase.insert(new Transaction(1, 50.00, new Date()));
transactionDatabase.insert(new Transaction(2, 20.00, new Date()));
transactionDatabase.insert(new Transaction(3, 110.00, new Date()));
transactionDatabase.insert(new Transaction(4, 250.00, new Date()));
transactionDatabase.insert(new Transaction(5, 5.00, new Date()));
transactionDatabase.insert(new Transaction(5, 73.00, new Date()));
List<Func1<Transaction, Boolean>> filters = new ArrayList<>();
filters.add(transaction -> transaction.transactionAmount > 20);
filters.add(transaction -> transaction.transactionAmount < 100);
transactionDatabase.getTransactions(filters)
.subscribe(System.out::println);
}
private class Transaction {
int transactionId;
double transactionAmount;
Date transactionDate;
public Transaction(int transactionId, double transactionAmount, Date transactionDate) {
this.transactionId = transactionId;
this.transactionAmount = transactionAmount;
this.transactionDate = transactionDate;
}
@Override
public String toString() {
return "Transaction{" +
"transactionId=" + transactionId +
", transactionAmount=" + transactionAmount +
", transactionDate=" + transactionDate +
'}';
}
}
class TransactionDatabase {
List<Transaction> transactions = new ArrayList<>();
public void insert(Transaction transaction) {
transactions.add(transaction);
}
public Observable<Transaction> getTransactions(List<Func1<Transaction, Boolean>> filters) {
Observable<Transaction> observable = Observable.from(transactions);
for (Func1<Transaction, Boolean> filter : filters) {
observable = observable.filter(filter);
}
return observable;
}
}
}
它会打印出来:
Transaction{transactionId=1, transactionAmount=50.0, transactionDate=Tue Jun 14 16:21:24 BRT 2016}
Transaction{transactionId=5, transactionAmount=73.0, transactionDate=Tue Jun 14 16:21:24 BRT 2016}
我认为这对你的问题来说是一个很好的解决方案。
希望它有所帮助。
祝你好运。