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 noticeably 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...)
UPDATE: 2022-10-24
As alluded to above, here's a little something I whipped up the other day in Go (now that generics are a thing):
func GetOrSetDefault[K comparable, V any](m map[K]V, key K, new_ func() V) V {
value, found := m[key]
if !found {
value = new_()
m[key] = value
}
return value
}
Enjoy!
a := make(map[int]string)
GetOrSetDefault(a, 42, func() string { return "hi" })
fmt.Println(a[42]) // hi