# Use Factory Methods for Collections

# Description

Java 9 introduced factory methods for creating immutable collections. This rule replaces the invocations of Collections.unmodifiable{List|Set|Map} with the corresponding factory method List.of (opens new window), Set.of (opens new window) and Map.ofEntries (opens new window) accordingly.

Requirements

Java 9

# Benefits

Remove verbosity and avoid creating intermediate collections only for the sake of initialization.

# Tags

# Code Changes

# Creating immutable List

Pre

    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list = Collections.unmodifiableList(list);

Post

    List<String> list = List.of("a", "b", "c");

# Creating immutable List with anonymous class

Pre

    List<String> list = Collections.unmodifiableList(new ArrayList<String>() {{
        add("a");
        add("b");
        add("c");
    }});

Post

    List<String> list = List.of("a", "b", "c");

# Creating immutable List form array

Pre

	List<String> list = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

Post

    List<String> list = List.of("a", "b", "c");

# Creating immutable Set

Pre

    Set<String> set = new HashSet<>();
    set.add("a");
    set.add("b");
    set.add("c");
    set = Collections.unmodifiableSet(set);

Post

    Set<String> set = Set.of("a", "b", "c");

# Creating immutable Map

Pre

    Map<String, String> map = new HashMap<>();
    map.put("1", "one");
    map.put("2", "two");
    map.put("3", "three");
    map = Collections.unmodifiableMap(map);

Post

    Map<String, String> map = Map.ofEntries(entry("1", "one"), entry("2", "two"), entry("3", "three"));

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID CollectionsFactoryMethods
First seen in jSparrow version 3.6.0
Minimum Java version 9
Remediation cost 5 min