115. Dissecting factory methods for collections
Using factory methods for collections is a must-have skill. It is very convenient to be able to quickly and effortlessly create and populate unmodifiable/immutable collections before putting them to work.
Factory methods for maps
For instance, before JDK 9, creating an unmodifiable map could be accomplished like this:
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java Coding Problems, First Edition");
map.put(2, "The Complete Coding Interview Guide in Java");
map.put(3, "jOOQ Masterclass");
Map<Integer, String> imap = Collections.unmodifiableMap(map);
This is useful if, at some point in time, you need an unmodifiable map from a modifiable one. Otherwise, you can take a shortcut as follows (this is known as the double-brace initialization technique and, generally, an anti-pattern):
Map<Integer, String> imap = Collections.unmodifiableMap(
new HashMap...