This post continues my exploration of Java9 features from my My Top Java 9 Features blog post. Here we are experimenting with Java9 Collections Static Factory Methods in the List, Set and Map interfaces.
Java9 makes it easier to create immutable lists using its new static Factory Methods
There are 12 Set.of and List.of methods –
jshell> Set.of() $1 ==> [] | created scratch variable $1 : Set
Note the inference as a List
To static
jshell> List.of("one","two","three") $2 ==> [one, two, three] | created scratch variable $2 : List
Note the inference as a List
The number of arguments keeps increasing until E e10, at which point we can use vararg –
static
Similarly Map defines –
jshell> Map.of() $12 ==> {} jshell> Map.of("key1", "value1", "key2", "value2") $13 ==> {key1=value1, key2=value2} | created scratch variable $13 : Map
Common characteristics of these static Factory Methods Lists, Sets and Maps are –
jshell> SetimmutableSet = Set.of("one","two","three") immutableSet ==> [three, two, one] | created variable immutableSet : Set jshell> immutableSet.add("four") | java.lang.UnsupportedOperationException thrown:
jshell> List
jshell> ListimmutableList = List.of("one","two","three") immutableList ==> [one, two, three] | created variable immutableList : List
jshell> Set.of("one","one") | java.lang.IllegalArgumentException thrown: duplicate element: one
jshell> Map.of("key1", "value1", "key1", "value2") | java.lang.IllegalArgumentException thrown: duplicate key: key1 | at ImmutableCollections$MapN.(ImmutableCollections.java:680) | at Map.of (Map.java:1326) | at (#15:1)
These are a useful and quick method for creating immutable collections, and jshell provides a good test ground to learn about the new methods and their associated characteristics