Social Media

Java9 JShell Examples : Collections Static Factory Methods

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.

Collections Static Factory Methods

Java9 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)

Examples

Note the inference as a List object

To static List of (E e1, E e2, E e3) –

Note the inference as a List object

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

static List of (E… elements)

Map

Similarly Map defines –

  • 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

Examples

Characteristics of Collections Static Factory Methods

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

  • Structurally Immutable – UnsupportedOperationException is thrown, although the elements themselves are immutable
  • No Nulls – NullPointerException thrown
  • Serialized – Serialized if elements 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 Keus – The Map will reject duplicate keys with IllegalArgumentException –
  • Iteration is also not guaranteed

Conclusions

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

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About

follow me on:

Leave a Comment:

Copyright 2013-2017 by javabullets.com   -  Designed by Thrive Themes | Powered by WordPress

Connect With Me: