How do I use new Java 10 methods like List.copyOf(), Set.copyOf(), and Map.copyOf()?

Java 10 introduced the List.copyOf(), Set.copyOf(), and Map.copyOf() methods as convenient ways to create unmodifiable copies of existing collections. These methods are part of the java.util package and provide a simpler way to create immutable collections compared to using older methods like Collections.unmodifiableList().

Here’s how you can use them:


1. List.copyOf()

The List.copyOf() method creates an unmodifiable copy of the provided Collection. The returned list:

  • Is immutable (you cannot add, remove, or modify elements).
  • Rejects null elements (throws a NullPointerException).

Example:

package org.kodejava.util;

import java.util.List;

public class ListCopyExample {
    public static void main(String[] args) {
        // Create a mutable list
        List<String> originalList = List.of("A", "B", "C");

        // Create an unmodifiable copy
        List<String> unmodifiableList = List.copyOf(originalList);

        // Print the copied list
        System.out.println(unmodifiableList);

        // Throws UnsupportedOperationException if modification is attempted
        // unmodifiableList.add("D");

        // Throws NullPointerException if original list has nulls
        // List<String> listWithNull = new ArrayList<>();
        // listWithNull.add(null);
        // List.copyOf(listWithNull);
    }
}

2. Set.copyOf()

The Set.copyOf() method creates an unmodifiable copy of the provided Collection, ensuring that:

  • The returned set contains no duplicate elements.
  • Null elements are not allowed.
  • The original collection can be a List, Set, or any Collection.

Example:

package org.kodejava.util;

import java.util.Set;

public class SetCopyExample {
   public static void main(String[] args) {
      // Create a mutable set
      Set<String> originalSet = Set.of("A", "B", "C");

      // Create an unmodifiable copy
      Set<String> unmodifiableSet = Set.copyOf(originalSet);

      // Print the copied set
      System.out.println(unmodifiableSet);

      // Throws UnsupportedOperationException
      // unmodifiableSet.add("D");
   }
}

3. Map.copyOf()

The Map.copyOf() method creates an unmodifiable copy of the provided map. Similar to List.copyOf() and Set.copyOf():

  • The returned map is immutable.
  • Null keys or values are not allowed.
  • Elements retain the original insertion order (if applicable, e.g., for LinkedHashMap).

Example:

package org.kodejava.util;

import java.util.Map;

public class MapCopyExample {
   public static void main(String[] args) {
      // Create a mutable map
      Map<Integer, String> originalMap = Map.of(1, "One", 2, "Two", 3, "Three");

      // Create an unmodifiable copy
      Map<Integer, String> unmodifiableMap = Map.copyOf(originalMap);

      // Print the copied map
      System.out.println(unmodifiableMap);

      // Throws UnsupportedOperationException
      // unmodifiableMap.put(4, "Four");
   }
}

Notes:

  1. Immutable Behavior:
    • Any attempt to modify the unmodifiable collections (e.g., using add() or put()) throws UnsupportedOperationException.
    • These methods return a new collection, but if the input collection is already immutable and meets the conditions, it may return the original collection (performance optimization).
  2. Handling Nulls:
    • If any input collection contains null elements, these methods will throw a NullPointerException.
  3. Differences from Existing Methods:
    • Unlike Collections.unmodifiableList()/Set()/Map(), these methods create a copy, ensuring that changes to the source collection won’t affect the new collection.
  4. Static Imports:
    • These methods belong to static utility classes (List, Set, and Map) and are invoked directly as static methods.

Summary:

  • Use these methods to get immutable copies of collections.
  • They reject null values by design.
  • Collections become unmodifiable and can’t be changed after creation.

They are great for enhancing immutability and safety of the application!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.