import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
public class RecordDeduplicator {
/**
* Deduplicates a list of records, considering a set of fields for uniqueness.
* This is designed for dry-run scenarios with rate limiting.
*
* @param records The list of records to deduplicate. Each record is assumed to be an object with fields.
* @param fieldExtractor A function that extracts the unique identifier fields from each record.
* @return A new list containing only the unique records.
*/
public static List<Object> deduplicate(List<?> records, FieldExtractor fieldExtractor) {
Set<String> seenKeys = new HashSet<>(); // Use a Set to efficiently track seen keys.
List<Object> uniqueRecords = new ArrayList<>();
for (Object record : records) {
String key = fieldExtractor.extractKey(record); // Extract the unique key from the record.
if (key == null) {
// Handle cases where key extraction fails. Could log an error.
continue; // Skip this record.
}
if (!seenKeys.contains(key)) {
seenKeys.add(key); // Mark the key as seen.
uniqueRecords.add(record); // Add the record to the unique list.
}
}
return uniqueRecords;
}
/**
* Functional interface to extract the unique key from a record.
*/
public interface FieldExtractor {
String extractKey(Object record);
}
public static void main(String[] args) {
// Example Usage (Dry-Run)
List<Object> data = new ArrayList<>();
data.add(new Record("1", "Alice", "123"));
data.add(new Record("2", "Bob", "456"));
data.add(new Record("1", "Alice", "123")); // Duplicate
data.add(new Record("3", "Charlie", "789"));
data.add(new Record("2", "Bob", "456")); // Duplicate
FieldExtractor extractor = record -> {
//Extract unique key based on ID field.
return ((Record)record).id;
};
List<Object> deduplicatedData = deduplicate(data, extractor);
System.out.println("Original Data: " + data);
System.out.println("Deduplicated Data: " + deduplicatedData);
}
//Simple record class for testing.
static class Record {
String id;
String name;
String value;
public Record(String id, String name, String value) {
this.id = id;
this.name = name;
this.value = value;
}
}
}
Add your comment