Immutable Collections in Java 9

in #java7 years ago (edited)

Immutable Collections in Java 9

In Java 9 we now have "immutable collections".

For example, if we want to create lists, we can do like this:

List<Integer> list0 = List.of(); // List0
List<Integer> list1 = List.of(10); // List1
List<Integer> list2 = List.of(10, 17); // List2
List<Integer> list3 = List.of(10, 17, 1); // ListN  

We can create sets in a similar way, like so:

Set<Integer> set0 = Set.of(); // List0
Set<Integer> set1 = Set.of(10); // List1
Set<Integer> set2 = Set.of(10, 17); // List2
Set<Integer> set3 = Set.of(10, 17, 1); // ListN
Set<Integer> set4 = Set.of(10, 17, 1, 2); // ListN

How can we do set operations? Let's take these sets:

Set<Integer> one = Set.of(1, 2, 3);
Set<Integer> two = Set.of(3, 4, 5);

To create a union of these is a bit uncomfortable, since there is no easy way to create an immutable Set from an ordinary Set. We could create a temporary Set and then the union from that, like so:

Set<Integer> temp = new HashSet<>(one);
temp.addAll(two);
Set<Integer> union = Set.of(temp.toArray(new Integer[0]));
System.out.println("Union = " + union);

If we do not like temporary variables, we could wrap this in a facade somewhere. To do the intersection is similar:

Set<Integer> temp = new HashSet<>(one);
temp.retainAll(two);
Set<Integer> intersection = Set.of(temp.toArray(new Integer[0]));
System.out.println("intersection = " + intersection);

We can also create Maps with Map.of():

Map<String, Integer> map0 = Map.of();
Map<String, Integer> map1 = Map.of("one", 1);
Map<String, Integer> map2 = Map.of("one", 1, "two", 2);

Map.of() works with key and value pairs up to 10 entries. Further that, we need to pass in a var-args of Entry instances and use Map.ofEntries(Entry...)

Map<String, Integer> mapN = Map.ofEntries(
    Map.entry("one", 1),
    Map.entry("two", 2),
    Map.entry("three", 3),
    Map.entry("four", 4),
    Map.entry("five", 5)
);

More info @ http://openjdk.java.net/jeps/269
Java 9: Factory Methods to Create Immutable Collections @ https://dzone.com/articles/java-9-factory-methods-to-create-immutable-collect

Sort:  

Nice tutorial. Thanks.

thanks. I just try to post here occasionally my Java9 learning path notes.