JShell Examples: Collections Static Factory Methods

DZone 's Guide to

JShell Examples: Collections Static Factory Methods

Explore Java 9's JShell and how you can use it to create static factory methods for collections, particularly with Lists, Sets, and Maps.

· Java Zone ·
Free Resource

This post continues my exploration of Java 9 features from my My Top Java 9 Features blog post. Here, we are experimenting with Java 9 Collections Static Factory Methods in the List, Set, and Map interfaces.

Collections Static Factory Methods

Java 9 makes it easier to create immutable lists using its new static Factory Methods.

List and Set

There are 12 Set.of and List.of methods:

  • List.of() or Set.of()
  • List.of(E e1) or Set.of(E e1) to E e10
  • List.of(E… elements) or Set.of(E… elements)


Note the inference as a List  object.

For a static List of (E e1, E e2, E e3):

Again, note the inference as a List object.

The number of arguments keeps increasing until E e10, at which point we can use vararg.


Similarly, Map defines a:

  • static Map of ()
  • static Map of (K k1, V v1) to (K k10, V v10)
  • static Map ofEntries (Map.Entry … entries) – note the use of Map.Entry


Characteristics of Collections Static Factory Methods

Common characteristics of these static Factory Methods for Lists, Sets, and Maps are:

  • Structurally Immutable: UnsupportedOperationException is thrown, although the elements themselves are immutable.
  • No Nulls: NullPointerException thrown.
  • Serialized – Serialized if elements are Serializable.

List-Specific Characteristics

  • Order – Order is maintained the same as elements input

Set Specific Characteristics

  • Reject Duplicates – The Set will also reject duplicates at creation time with an IllegalArgumentException:

Map Specific Characteristics

  • Reject Duplicate Keys – The Map will reject duplicate keys with IllegalArgumentException –
  • Iteration is also not guaranteed

These are useful and quick methods for creating immutable collections, and JShell provides a good testing ground to learn about the new methods and their associated characteristics.

collections, factory methods, java, java 9, jshell, tutorial

Published at DZone with permission of Martin Farrell , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}