Java 9 Even More Good – Part 3 (Collection Factory Methods)

Once there was hope for collection literals. Wouldn’t this be great?

List<String> list = [ “a”, “b”, “c” ];
Map<String, Integer> map = [ “one” = 1, “two” = 2, “three” = 3 ];

But we have something like this because there are some reason that java 9 can’t do this

List<String> list = List.of(“a”, “b”, “c”);
Map<String, Integer> mapImmediate = Map.of(
“one”, 1,
“two”, 2,
“three”, 3);

Map<String, Integer> mapEntries = Map.ofEntries(
entry(“one”, 1),
entry(“two”, 2),
entry(“three”, 3));

Not bad either. This will make the creation of ad-hoc collections, especially for static fields, much more convenient. There are a couple of interesting things to note about these collections

First of all, they are all immutable. That’s right,

List.of(“a”).add(“b”) fails (with an UnsupportedOperationException).

I like it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s