Why Java Introduced List.of() Method?

  • Post last modified:September 14, 2023
  • Reading time:2 mins read

Inspiration for List.of() method In Java

TLDR;

  • The `List.of()` method introduced in Java 9 provides a convenient way to generate immutable lists.
  • It was a progressive step from JDK developers to provide concise and expressive ways to work with collections.

Inspiration

  • The main context and inspiration behind the addition of this method was following trends in functional programming languages.
  • Languages like Haskell promoted immutability and many languages followed in their footsteps.

Immutability

  • Immutable collections allow us to write code in a functional style and avoid concurrency issues.
  • Since any modification to the collection would produce a new collection, the original collection doesn’t get mutated. This is important since now each thread can have its own collection without having to access a shared collection.
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
 at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
 at ListOfFeature.main(ListOfFeature.java:13)

Readability

  • It aligns with the JDK developer’s effort to make code more concise and readable.
  • `List.of` method allows the developer to create a list with minimal code.

Functional Programming

  • The introduction of Streams API allowed Java developers to process the elements in the collection as streams of data.
  • `List.of` complements this effort since it provides an immutable list that can be integrated with Streams API very nicely.

Other Methods

  • Like `List`, `Set`, and `Map` also have been provided with methods to create immutable collections.
  • Set has `Set.of` method while Map has `Map.of` and `Map.ofEntries` methods.

Before You Leave

Leave a Reply