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.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Initialize the
seen
variable as an emptySet
. - Add transactions to
seen
if you've not encountered them before. - Return the appropriate boolean value if the loop ends without finding a duplicate.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.*;
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
____
}
}
// Return true/false if no duplicates found
return ____;
}
}