Ich experimentiere mit einem einfachen Programm, das ein Bankkonto erstellt und Transaktionen daran gebunden hat. Es funktioniert fehlerfrei, wenn ich primitive Typen verwende, jedoch habe ich eine Möglichkeit hinzugefügt, eine String-Operation hinzuzufügen (wie zB ERROR beim Zurückziehen), und jetzt weiß ich nicht, wie ich die Liste sortieren kann, damit die String-Operationen nicht erscheinen alle, wenn sie ausgedruckt, gefiltert oder am unteren Rand angezeigt werden, wenn sie sortiert sind.Vergleichen und sortieren von parametrisierten Typen in einer Liste?
vollständige Quellcode:
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;
}
}
dachte darüber nach, aber ich dachte auch bereits bestehende Möglichkeit zu vergleichen und/oder Art verschiedene Typen. Danke trotzdem für das Beispiel! – ForInfinity