Skip to content

Instantly share code, notes, and snippets.

@eyalgo
Last active August 29, 2015 13:58
Show Gist options
  • Save eyalgo/10110666 to your computer and use it in GitHub Desktop.
Save eyalgo/10110666 to your computer and use it in GitHub Desktop.
Safe get from map that holds Collection as value
// The code
public static <T, V> Collection<V> safeGetCollectionFromMap(Map<T, ? extends Collection<V>> map, T key) {
if (map.get(key) != null) {
return map.get(key);
} else {
return Lists.newLinkedList();
}
}
// The tests
//import static <package>.CollectionUtils.safeGetCollectionFromMap;
@Test
public void mapContainsKey_thenShouldReturnTheValue() {
Collection<String> values = Sets.newHashSet("v1", "v2");
Map<String, Set<String>> map = ImmutableMap.<String, Set<String>>builder().put("the-key", Sets.newHashSet("v1", "v2")).build();
assertThat(safeGetCollectionFromMap(map, "the-key"), equalTo(values));
}
@Test
public void mapDoesNotContainsKey_thenShouldReturnEmpty() {
Map<String, Set<String>> map = ImmutableMap.<String, Set<String>>builder().put("the-key", Sets.newHashSet("v1", "v2")).build();
assertThat(safeGetCollectionFromMap(map, "the-OTHER-key"), is(emptyCollectionOf(String.class)));
}
@Test
public void mapContainsKeyWithNullValue_thenShouldReturnEmpty() {
Map<String, Set<String>> map = new HashMap<String, Set<String>>();
map.put("the-key", null);
assertThat(safeGetCollectionFromMap(map, "the-key"), is(emptyCollectionOf(String.class)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment