eyalgo
4/8/2014 - 11:12 AM

Safe get from map that holds Collection as value

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)));
}