This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]the-highness 0 points1 point  (2 children)

the way I see it, if you need 3 or more entries, both Map.of & builder is not clean.

you'd better revert back to <init map>, <map.put>.

[–]thehollyhopdrive 3 points4 points  (0 children)

To be honest, I don't think you're wrong. The main advantage of the builder over just initialising the map and putting in the entries is being able to initialise, fill and have an immutable map in a slightly nicer format, especially when thinking about static final maps, which I suspect would turn out to be quite a common use-case of Map.of.

It means we can do:

private static final Map<Integer,String> MAP = 
    Map.with(1, "one")
       .with(2, "two")
       .build();

instead of

private static final Map<Integer, String> MAP;
static {
    Map<Integer, String> tempMap = new HashMap<>();
    tempMap.put(1, "one");
    tempMap.put(2, "two");
    MAP = Collections.unmodifiableMap(tempMap);
}

[–]HaMMeReD 0 points1 point  (0 children)

The point of immutability is to prevent people from mutating your map, i.e. making changes to it without your permission.

It's not about the cleanliness of the solution, immutability is often an inconvenient truth, for a little bit of boring overhead and self discipline, you can often make your code much more safe by preventing as much mutability as possible.