I'm back doing Java stuff for a while, and a lot of our codebase uses Maps a lot. Though it's a new project, the codebase leans heavily on the style of Java 7/8 and not with the new patterns that came with Java 9 and above. Here are some things that I have learned lately.
Creation
I've seen this pattern many times over my career and never loved it:
Map<String,String> myMap = new HashMap<>();
myMap.put("A","B");
myMap.put("C","D");
myMap.put("E","F");
// ....
Java 9 introduced better ways to initialize a map. The simplest:
Map<String,String> myMap = Map.of("A","B","C","D","E","F");
Keys and values go in alternating order. One catch: Map.of only supports up to 10 entries. For larger maps, there's Map.ofEntries:
Map<String,String> myMap = Map.ofEntries(Map.Entry("A","B"),
Map.Entry("C","D"),
Map.Entry("E","F"));
More verbose, but still much cleaner than the old approach and there's no entry limit.
Testing for Empty
Empty-checking in Java is trickier than it should be. If the object might be null, the naive check becomes:
if (myMap==null || myMap.isEmpty()) { ///
That gets old fast. Apache Common Collections has a cleaner option and chances are it's already in your project even if you didn't add it explicitly:
if (MapUtils.isEmpty(myMap)) {////
MapUtils handles the null check for you. Worth noting: you can't use CollectionUtils here — it won't compile, because Map doesn't implement Collection in the Java type hierarchy. You can also get an immutable empty map from standard Java:
Map<String,String> myMap = Collections.emptyMap();
So Collections considers Map a collection but not CollectionUtils. Java consistency at its finest.
Coming back to a Java codebase after time away is a strange experience. The language has genuinely improved, but the old patterns are still used everywhere, written by people who had no reason to change them. I suspect I'll be finding these kinds of small upgrades for a while.