# 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"));

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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