Java 9 Collection Factory Methods
In Java 9, the new static factory methods in the List, Set and Map interfaces can create immutable instances of these collections.
These factory methods provide a more concise way to create collections.
Creating a collection the old way
Example
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Collections
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
HashSet
;
import
java
.
util
.
List
;
import
java
.
util
.
Map
;
import
java
.
util
.
Set
;
public
class
Tester
{
public
static
void
main
(
String
[
]
args
)
{
Set
<
String
set
=
new
HashSet
<>
(
);
set
.
add
(
"
A
"
)
;
set
.
add
(
"
B
"
)
;
set
.
add
(
"
C
"
)
;
set
=
Collections
.
unmodifiableSet
(
set
)
;
System
.
out
.
println
(
set
)
;
List
<
String
list
=
new
ArrayList
<>
(
);
list
.
add
(
"
A
"
)
;
list
.
add
(
"
B
"
)
;
list
.
add
(
"
C
"
)
;
list
=
Collections
.
unmodifiableList
(
list
)
;
System
.
out
.
println
(
list
)
;
Map
<
String
,
String
map
=
new
HashMap
<>
(
);
map
.
put
(
"
A
"
,
"
Apple
"
)
;
map
.
put
(
"
B
"
,
"
Boy
"
)
;
map
.
put
(
"
C
"
,
"
Cat
"
)
;
map
=
Collections
.
unmodifiableMap
(
map
)
;
System
.
out
.
println
(
map
)
;
}
}
The execution output is:
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
Creating a collection the new way
In Java 9, the following methods are added to the List, Set and Map interfaces and their overloaded counterparts.
static List of(E e1, E e2, E e3);
static Set of(E e1, E e2, E e3);
static Map of(K k1, V v1, K k2, V v2, K k3, V v3);
static Map ofEntries(Map.Entry extends K,? extends V>... entries)
-
List and Set interfaces: the of(...) method is overloaded with variants taking 0 to 10 arguments.
-
Map interface: the of(...) method is overloaded with variants taking 0 to 10 arguments.
-
For the Map interface, if there are more than 10 arguments, you can use the ofEntries(...) method.
Creating a collection the new way
Example
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Collections
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
HashSet
;
import
java
.
util
.
List
;
import
java
.
util
.
AbstractMap
;
import
java
.
util
.
Map
;
import
java
.
util
.
Set
;
public
class
Tester
{
public
static
void
main
(
String
[
]
args
)
{
Set
<
String
set
=
Set.
of
(
"
A
"
,
"
B
"
,
"
C
"
)
;
System
.
out
.
println
(
set
)
;
List
<
String
list
=
List.
of
(
"
A
"
,
"
B
"
,
"
C
"
)
;
System
.
out
.
println
(
list
)
;
Map
<
String
,
String
map
=
Map.
of
(
"
A
"
,
"
Apple
"
,
"
B
"
,
"
Boy
"
,
"
C
"
,
"
Cat
"
)
;
System
.
out
.
println
(
map
)
;
Map
<
String
,
String
map1
=
Map.
ofEntries
(
new
AbstractMap
.
SimpleEntry
<>
(
"
A
"
,
"
Apple
"
)
,
new
AbstractMap
.
SimpleEntry
<>
(
"
B
"
,
"
Boy
"
)
,
new
AbstractMap
.
SimpleEntry
<>
(
"
C
"
,
"
Cat
"
)
)
;
System
.
out
.
println
(
map1
)
;
}
}
The output is:
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
{A=Apple, B=Boy, C=Cat}
Java 9 New Features