我正在試驗一個簡單的程序,該程序創建一個銀行賬戶並且有與之相關的交易。它在我使用基本類型時完美地工作,但是我包括添加一個String操作的可能性(例如退出時的錯誤),現在我不確定如何對列表排序,以便字符串操作不會出現在全部打印出來,如果過濾,或者如果排序出現在底部。比較和排列列表中的參數化類型?
完整的源代碼:
public static void main(String[] args) {
BankAccount bankAccount = new BankAccount();
bankAccount.addTransaction(2, TransactionType.DEPOSIT);
bankAccount.addTransaction(100.66, TransactionType.DEPOSIT);
bankAccount.addTransaction(2, TransactionType.WITHDRAW);
bankAccount.addTransaction("ERROR", TransactionType.WITHDRAW);
List<Transaction> transactions = bankAccount.getTransactions();
List<Transaction> collect = transactions.stream()
//Error appears over here, probably due to wrong syntax of the two next lines.
.sorted(Comparator.comparing((Transaction tr) -> tr.getAmount()).reversed())
.filter(tr -> tr.getAmount() > 0)
.collect(toList());
collect.forEach(tr -> System.out.println(tr));
}
private static class BankAccount {
private List<Transaction> transactions = new ArrayList<>();
public <T> void addTransaction(T amount, TransactionType transactionType) {
Transaction transaction = new Transaction(amount, transactionType);
transactions.add(transaction);
//return 0;
}
public List<Transaction> getTransactions() {
return Collections.unmodifiableList(transactions);
}
@Override
public String toString() {
return "BankAccount{" +
"transactions=" + transactions +
'}';
}
}
private static class Transaction<T> {
private final T amount;
private final TransactionType transactionType;
private final Date dateCreated;
public Transaction(T amount, TransactionType transactionType) {
this.amount = amount;
this.transactionType = transactionType;
this.dateCreated = new Date();
}
public T getAmount() {
return amount;
}
public TransactionType getTransactionType() {
return transactionType;
}
public Date getDateCreated() {
return dateCreated;
}
@Override
public String toString() {
return "Transaction{" +
"amount=" + amount +
", transactionType=" + transactionType +
", dateCreated=" + dateCreated +
'}';
}
}
private static enum TransactionType {
DEPOSIT, WITHDRAW;
}
}
想過這個問題,但我還以爲已經有現有的方法來比較和/或種類不同的類型。儘管如此,謝謝你的例子! – ForInfinity