import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
public class DuplicateRemover {
/**
* Removes duplicate form field values from a map of field names to values.
* Handles potential null values gracefully.
*
* @param formFields A map where keys are form field names (Strings) and values are field values (Strings).
* @return A new map with duplicate values removed. Returns an empty map if the input is null.
*/
public static Map<String, String> removeDuplicateValues(Map<String, String> formFields) {
if (formFields == null) {
return new HashMap<>(); // Handle null input gracefully
}
Set<String> seenValues = new HashSet<>(); // Use a set to efficiently track seen values
Map<String, String> uniqueFields = new HashMap<>();
for (Map.Entry<String, String> entry : formFields.entrySet()) {
String fieldName = entry.getKey();
String fieldValue = entry.getValue();
if (fieldValue != null) { // Handle null values
if (!seenValues.contains(fieldValue)) {
uniqueFields.put(fieldName, fieldValue);
seenValues.add(fieldValue);
}
} else {
//If value is null, skip that field
//Alternatively, could store null in the unique map if desired.
}
}
return uniqueFields;
}
public static void main(String[] args) {
//Example Usage
Map<String, String> formData = new HashMap<>();
formData.put("name", "John");
formData.put("age", "30");
formData.put("city", "New York");
formData.put("occupation", "Engineer");
formData.put("age", "30"); // Duplicate age
formData.put("country", null);
formData.put("city", "London"); //Duplicate city
Map<String, String> uniqueData = removeDuplicateValues(formData);
System.out.println(uniqueData); //Output: {name=John, age=30, city=New York, occupation=Engineer, country=null}
}
}
Add your comment