Saturday, December 3, 2016

Day 3, Java Holiday Calendar 2016, Initialize Maps

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")).

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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.