Use Factory Methods for Collections

Properties

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

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, Set.of and Map.ofEntries accordingly.

Benefits

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

Requirement & Tags

Requirements

Java 9

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