Headers { public static ImmutableMap<String, List<String>> mergeHeaders( Map<String, List<String>> oldHeaders, Map<String, List<String>> newHeaders) { ImmutableMap.Builder<String, List<String>> headersBuilder = ImmutableMap.builder(); for (Map.Entry<String, List<String>> entry : oldHeaders.entrySet()) { String key = entry.getKey(); List<String> oldValue = entry.getValue(); List<String> newValue = newHeaders.get(key); ImmutableList.Builder<String> mergedValueBuilder = ImmutableList.builder(); mergedValueBuilder.addAll(oldValue); if (newValue != null) { mergedValueBuilder.addAll(newValue); } headersBuilder.put(key, mergedValueBuilder.build()); } for (Map.Entry<String, List<String>> entry : newHeaders.entrySet()) { String key = entry.getKey(); if (!oldHeaders.containsKey(key)) { headersBuilder.put(key, ImmutableList.copyOf(entry.getValue())); } } return headersBuilder.build(); }  static ImmutableMap<String, List<String>> mergeHeaders(
      Map<String, List<String>> oldHeaders, Map<String, List<String>> newHeaders);  }
@Test public void testMergeHeaders() { Map<String, List<String>> headers1 = createHeaders("key1", "value1", "key1", "value2"); Map<String, List<String>> headers2 = createHeaders("key1", "value2", "key2", "value2"); Map<String, List<String>> mergedHeaders = Headers.mergeHeaders(headers1, headers2); Map<String, List<String>> expectedHeaders = createHeaders("key1", "value1", "key1", "value2", "key1", "value2", "key2", "value2"); assertThat(mergedHeaders).containsExactlyEntriesIn(expectedHeaders); }
@Test public void testMergeHeadersEmpty() { Map<String, List<String>> headers1 = createHeaders(); Map<String, List<String>> headers2 = createHeaders("key1", "value1", "key2", "value2"); Map<String, List<String>> mergedHeaders = Headers.mergeHeaders(headers1, headers2); Map<String, List<String>> expectedHeaders = createHeaders("key1", "value1", "key2", "value2"); assertThat(mergedHeaders).containsExactlyEntriesIn(expectedHeaders); }