Convenience Factory Methods for Java Collections

This article presents convenience factory methods for collections introduced in JDK 9. The JEP (Java Enhancement Process) 269 brings new APIs to make it convenient to create instances of collections and maps with small numbers of elements.

The purpose was to ease the pain of not having collection literals in the Java programming language. The API is deliberately kept minimal.

It contains new static factory methods on the List, Set, and Map interfaces for creating unmodifiable instances of collections.

Installing JDK 9 EA

We download JDK 9 early access from jdk9.java.net/download/.

$ tar vzfx jdk-9-ea+131_linux-x64_bin.tar.gz

On Linux, we decompress the jdk-9-ea+131_linux-x64_bin.tar.gz file.

$ cd jdk-9/ 
$ ./bin/java -version
java version "9-ea"
Java(TM) SE Runtime Environment (build 9-ea+131)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+131, mixed mode)

We move to the root directory and show the version of Java.

At this moment, neither NetBeans nor Eclipse support JDK 9; therefore, we will run our examples from command line.

There are three new static overloaded methods:

The methods create unmodifiable instances of the respective collections.

List example

The first example creates a list with the new API. A list is a simple ordered collection that allows duplicate elements.

$ tree
.
└── com
    └── zetcode
        └── ListExample.java

2 directories, 1 file

We have this project directory structure.

ListExample.java
package com.zetcode;

import java.util.List;

public class ListExample {

    public static void main(String[] args) {
    
        List<String> fruits = List.of("apple", "banana", "plum", "lemon");
        System.out.println(fruits);
        
        String[] items = {"coin", "pen", "bottle", "spoon"};
        
        List<String> listOfItems = List.of(items);
        System.out.println(listOfItems);
    }
}

In the example, we create two lists of strings with the new List.of() method call.

List<String> fruits = List.of("apple", "banana", "plum", "lemon");

A new list is created. The items are specified as List.of() parameters.

String[] items = {"coin", "pen", "bottle", "spoon"};

List<String> listOfItems = List.of(items);

The List.of() can also take an array as a parameter.

$ ~/bin/jdk1.9/bin/javac -d bin com/zetcode/ListExample.java

We compile the code example. The binaries are put into the bin directory.

$ ~/bin/jdk1.9/bin/java -cp bin com.zetcode.ListExample 
[apple, banana, plum, lemon]
[coin, pen, bottle, spoon]

We run the example. The two lists are printed to the console.

Set example

In the following example, we show the new API for the Set collection. A set is a collection that contains no duplicate elements.

SetExample.java
package com.zetcode;

import java.util.Set;
import java.util.TreeSet;

public class SetExample {

    public static void main(String[] args) {
    
        Set<String> colours = Set.of("blue", "red", "green", "yellow");
        System.out.println(colours);
        
        String[] names = {"Jane", "Paul", "Robin", "Susan", 
                "Monica", "Jan", "Peter"};
        
        TreeSet<String> setOfnames = new TreeSet<String>(Set.of(names));
        System.out.println(setOfnames);
    }
}

Two sets are created; the second one is alphabetically sorted.

Set<String> colours = Set.of("blue", "red", "green", "yellow");

A new set is created with the Set.of() method call.

String[] names = {"Jane", "Paul", "Robin", "Susan", 
        "Monica", "Jan", "Peter"};

TreeSet<String> setOfnames = new TreeSet<String>(Set.of(names));

To create a sorted set, we pass the created set to the TreeSet.

$ ~/bin/jdk1.9/bin/javac -d bin com/zetcode/SetExample.java 
$ ~/bin/jdk1.9/bin/java -cp bin com.zetcode.SetExample 
[yellow, red, green, blue]
[Jan, Jane, Monica, Paul, Peter, Robin, Susan]

We compile and run the example.

Map example

The next two examples present the new API for the Map collection. A map is a collection that contains unique key-value pairs.

MapExample.java
package com.zetcode;

import java.util.Map;

public class MapExample {

    public static void main(String[] args) {
    
        Map<String, Integer> items = Map.of("coins", 12, "chairs", 4, "pens", 2);
        items.entrySet().stream().forEach(System.out::println);
    }
}

The Map.of() method creates a new map with two key-value pairs.

$ ~/bin/jdk1.9/bin/javac -d bin com/zetcode/MapExample.java 
$ ~/bin/jdk1.9/bin/java -cp bin com.zetcode.MapExample 
coins=12
chairs=4
pens=2

We compile and run the program.

In the second example, we create map elements with the Map.entry(). A map entry is a key-value pair.

MapExample2.java
package com.zetcode;

import java.util.Map;
import static java.util.Map.entry;

public class MapExample2 {

    public static void main(String[] args) {
    
        Map<Integer,String> map = Map.ofEntries(
            entry(1, "A"),
            entry(2, "B"),
            entry(3, "C"),
            entry(4, "D")
        );
        
        map.entrySet().stream().forEach(System.out::println);
    }
}

A new map of entries is created with the Map.ofEntries() method.

$ ~/bin/jdk1.9/bin/javac -d bin com/zetcode/MapExample2.java 
$ ~/bin/jdk1.9/bin/java -cp bin com.zetcode.MapExample2 
1=A
2=B
3=C
4=D

We compile and run the program.

In this article, we have looked at the new collection API in the upcoming JDK 9.

You might also be interested in the following related tutorials: Java tutorial, Joining strings with Java 8's StringJoiner, or Introduction to Google Guava.