I love just about everything I have seen from Kotlin, but the snippet you added can be closely replicated in Java 8:
publicstaticvoidmain(String[]args){/* Init Map */Map<String,List<Integer>>myMap=newHashMap<>();List<Integer>l=newArrayList<>();l.add(32);myMap.put("aaa",l);/* New kv pair */Stringkey="aaa";Integervalue=2;/* Add the new value */myMap.computeIfAbsent(key,k->newArrayList<>()).add(value);}
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I love just about everything I have seen from Kotlin, but the snippet you added can be closely replicated in Java 8:
Hi Evan, thank you for this snippet! I wasn't familiar with computeIfAbsent method. :)
No problem! It is amusing watching Java add a lot of these kinds of features from Scala and Kotlin.
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) );
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.