Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Holiday Calendar 2016 (Day 3): Initializing Maps in the Smartest Way

DZone's Guide to

Java Holiday Calendar 2016 (Day 3): Initializing Maps in the Smartest Way

Learn how you can create and initialize type-safe maps in Java by using two simple utility methods.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Image title

Today's tip 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());
    }


You can read more about initializing maps here.

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

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,maps ,immutable ,type-safe

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}