Nifty Bits of Java

Mostly discovered via Intellij's very helpful suggestions.

September 16, 2021

I'm building me first real(-ish) java project. I did some C# development about a decade ago. Since then I've mostly used (and enjoyed) Go. Now that I'm diving into Clojure I think having some direct experience with Java and the JVM is going to help out. For the most part, it feels a lot like C#, but there are some noticably nice, fancy features. Here's one I quite like:

computeIfAbsent

Given, say, a HashMap<String, ArrayList<String>>, and you want to add a value to the ArrayList that corresponds to a key that already exists, or maybe the value in question is the first for that key, so we have to be careful. My first draft came out looking like this:

var m = new HashMap<String, ArrayList<String>>();
...
var listing = m.get("key");
if (listing == null) {
	listing = new ArrayList<String>();
	m.put("key", listing);
}
listing.add("new-value");

(Don't ask me how many times I've written that kind of code in other languages like C# and Go...)

Well, my nifty editor, Intellij, made the following nifty suggestion:

var m = new HashMap<String, ArrayList<String>>();
...
m.computeIfAbsent("key", k -> new ArrayList<>());
m.get("key").add("new-value");

(Hopefully now that generics are [soon?] coming to Go, similar behavior will appear for that community...)