Implementing a duplicate transaction finder
Financial transaction logs must be validated to ensure each transaction ID is unique. Your task is to implement a method that efficiently checks for the presence of any duplicate transaction IDs.
Diese Übung ist Teil des Kurses
Optimizing Code in Java
Anleitung zur Übung
- Initialize the
seenvariable as an emptySet. - Add transactions to
seenif you've not encountered them before. - Return the appropriate boolean value if the loop ends without finding a duplicate.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
public class Main {
public static void main(String[] args) {
TransactionProcessor processor = new TransactionProcessor();
String[] transactions = {
"TXN001", "TXN002", "TXN003", "TXN001",
"TXN004", "TXN005", "TXN003", "TXN006"
};
boolean hasDuplicates = processor.hasDuplicateTransactions(transactions);
if (hasDuplicates) {
System.out.println("Duplicate transactions detected!");
} else {
System.out.println("All transactions are unique.");
}
}
}
class TransactionProcessor {
public boolean hasDuplicateTransactions(String[] transactionIds) {
// Initialize an empty HashSet
____ seen = new ____<>();
for (String transactionId : transactionIds) {
if (seen.contains(transactionId)) {
return true;
} else {
// First time seeing this transaction, add it to the set
seen.____(____)
}
}
// Return true/false if no duplicates found
return ____;
}
}