1. import java.util.HashSet;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.HashMap;
  5. public class DuplicateRemover {
  6. /**
  7. * Removes duplicate form field values from a map of field names to values.
  8. * Handles potential null values gracefully.
  9. *
  10. * @param formFields A map where keys are form field names (Strings) and values are field values (Strings).
  11. * @return A new map with duplicate values removed. Returns an empty map if the input is null.
  12. */
  13. public static Map<String, String> removeDuplicateValues(Map<String, String> formFields) {
  14. if (formFields == null) {
  15. return new HashMap<>(); // Handle null input gracefully
  16. }
  17. Set<String> seenValues = new HashSet<>(); // Use a set to efficiently track seen values
  18. Map<String, String> uniqueFields = new HashMap<>();
  19. for (Map.Entry<String, String> entry : formFields.entrySet()) {
  20. String fieldName = entry.getKey();
  21. String fieldValue = entry.getValue();
  22. if (fieldValue != null) { // Handle null values
  23. if (!seenValues.contains(fieldValue)) {
  24. uniqueFields.put(fieldName, fieldValue);
  25. seenValues.add(fieldValue);
  26. }
  27. } else {
  28. //If value is null, skip that field
  29. //Alternatively, could store null in the unique map if desired.
  30. }
  31. }
  32. return uniqueFields;
  33. }
  34. public static void main(String[] args) {
  35. //Example Usage
  36. Map<String, String> formData = new HashMap<>();
  37. formData.put("name", "John");
  38. formData.put("age", "30");
  39. formData.put("city", "New York");
  40. formData.put("occupation", "Engineer");
  41. formData.put("age", "30"); // Duplicate age
  42. formData.put("country", null);
  43. formData.put("city", "London"); //Duplicate city
  44. Map<String, String> uniqueData = removeDuplicateValues(formData);
  45. System.out.println(uniqueData); //Output: {name=John, age=30, city=New York, occupation=Engineer, country=null}
  46. }
  47. }

Add your comment