DEV Community

Discussion on: A small piece of code which is going to inspire you to try out Kotlin

Collapse
 
evanoman profile image
Evan Oman • Edited

I love just about everything I have seen from Kotlin, but the snippet you added can be closely replicated in Java 8:

public static void main(String[] args)
{
    /* Init Map */
    Map<String, List<Integer>> myMap = new HashMap<>();
    List<Integer> l = new ArrayList<>();
    l.add(32);
    myMap.put("aaa", l);

    /* New kv pair */
    String key = "aaa";
    Integer value = 2;

    /* Add the new value */
    myMap.computeIfAbsent(key, k -> new ArrayList<>())
            .add(value);
}
Collapse
 
pozo profile image
Zoltan Polgar

Hi Evan, thank you for this snippet! I wasn't familiar with computeIfAbsent method. :)

Collapse
 
evanoman profile image
Evan Oman

No problem! It is amusing watching Java add a lot of these kinds of features from Scala and Kotlin.

Collapse
 
florianschaetz profile image
(((Florian Schätz)))

Java 9 will also have some nice factory methods, so you will probably be able to write something like...

Map map = Map.of("aaa", List.of(32) );

Collapse
 
nurettin profile image
Nurettin Onur TUĞCU • Edited

Actually, the java example is better, since the lambda is lazily evaluated. putIfAbsent will always try to construct it's second argument even if it isn't in the map. However, that doesn't mean you can't use it in kotlin as well.