Day 3, Java Holiday Calendar 2016, Initialize Maps

by Per Minborg

on December 3, 2016

3. Initializing Maps in the Smartest Way


Today's tips is how to initialize Java Maps in a type safe way with Java 8. With Java 9, we will get even better ways of creating immutable Maps. Until then, by defining two utility methods:

    public static <K, V> Entry<K, V> entry(K key, V value) {
return new AbstractMap.SimpleEntry<>(key, value);
}

public static <K, U> Collector<Entry<K, U>, ?, Map<K, U>> entriesToMap() {
return Collectors.toMap(Entry::getKey, Entry::getValue);
}

You Can Do This:

protected static Map<Integer, String> createMap() {
return Stream.of(
entry(0, "zero"),
entry(1, "one"),
entry(2, "two"),
entry(3, "three"),
entry(4, "four"),
entry(5, "five"),
entry(6, "six"),
entry(7, "seven"),
entry(8, "eight"),
entry(9, "nine"),
entry(10, "ten"),
entry(11, "eleven"),
entry(12, "twelve")).
collect(entriesToMap());
}

Read more in the original article at http://minborgsjavapot.blogspot.com/2014/12/java-8-initializing-maps-in-smartest-way.html

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

About

Per Minborg

Per Minborg is a Palo Alto based developer and architect, currently serving as CTO at Speedment, Inc. He is a regular speaker at various conferences e.g. JavaOne, DevNexus, Jdays, JUGs and Meetups. Per has 15+ US patent applications and invention disclosures. He is a JavaOne alumni and co-author of the publication “Modern Java”.