1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.stream.Collectors;
  4. public class HeaderDeduplicator {
  5. public static Map<String, String> deduplicateHeaders(Map<String, String> headers) {
  6. Map<String, String> deduplicated = new HashMap<>();
  7. for (Map.Entry<String, String> entry : headers.entrySet()) {
  8. String key = entry.getKey();
  9. String value = entry.getValue();
  10. if (value != null && !value.trim().isEmpty()) { // Sanity check: value not null or empty
  11. if (!deduplicated.containsKey(key)) {
  12. deduplicated.put(key, value);
  13. }
  14. }
  15. }
  16. return deduplicated;
  17. }
  18. public static void main(String[] args) {
  19. // Example usage
  20. Map<String, String> headers = new HashMap<>();
  21. headers.put("Content-Type", "application/json");
  22. headers.put("Content-Type", "application/json"); // Duplicate
  23. headers.put("X-Custom-Header", "value1");
  24. headers.put("X-Custom-Header", "value2"); // Duplicate
  25. headers.put("Status", "200 OK");
  26. headers.put(" ", ""); //Empty string
  27. headers.put(null, null); //Null value
  28. Map<String, String> deduplicatedHeaders = deduplicateHeaders(headers);
  29. // Print the deduplicated headers
  30. deduplicatedHeaders.forEach((key, value) -> System.out.println(key + ": " + value));
  31. }
  32. }

Add your comment