import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class HeaderDeduplicator {
public static Map<String, String> deduplicateHeaders(Map<String, String> headers) {
Map<String, String> deduplicated = new HashMap<>();
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (value != null && !value.trim().isEmpty()) { // Sanity check: value not null or empty
if (!deduplicated.containsKey(key)) {
deduplicated.put(key, value);
}
}
}
return deduplicated;
}
public static void main(String[] args) {
// Example usage
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Content-Type", "application/json"); // Duplicate
headers.put("X-Custom-Header", "value1");
headers.put("X-Custom-Header", "value2"); // Duplicate
headers.put("Status", "200 OK");
headers.put(" ", ""); //Empty string
headers.put(null, null); //Null value
Map<String, String> deduplicatedHeaders = deduplicateHeaders(headers);
// Print the deduplicated headers
deduplicatedHeaders.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Add your comment