Skip to content

Instantly share code, notes, and snippets.

@nbuesing
Last active November 15, 2018 20:09
Show Gist options
  • Save nbuesing/cd534d3619b3062372d2 to your computer and use it in GitHub Desktop.
Save nbuesing/cd534d3619b3062372d2 to your computer and use it in GitHub Desktop.
package com.objectpartners.buesing.util;
import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.objectpartners.buesing.util.MapUtils.entry;
/**
* @author Neil Buesing
*/
public class MapInitializationTest {
//the approach described in this blog
private Map<String, Integer> mapA = MapUtils.asMap(entry("A", 1), entry("B", 2));
//the approach described in this blog (unmodifiable)
private Map<String, Integer> mapB = MapUtils.asUnmodifiableMap(entry("A", 1), entry("B", 2));
//block initialization
private Map<String, Integer> mapC = new HashMap<String, Integer>();
{
mapA.put("A", 1);
mapA.put("B", 2);
}
//block initialization / unmodifiable
private Map<String, Integer> mapD;
{
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
mapD = Collections.unmodifiableMap(map);
}
//inheritance with block initialization
private Map<String, Integer> mapE = new HashMap<String, Integer>() {{
put("A", 1);
put("B", 2);
}};
//3rd party library Guava
private Map mapF = ImmutableMap.builder().put("A", 1).put("B", 2).build();
@Test
public void test() {
Assert.assertEquals(mapA, mapB);
Assert.assertEquals(mapA, mapC);
Assert.assertEquals(mapA, mapD);
Assert.assertEquals(mapA, mapE);
Assert.assertEquals(mapA, mapF);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment