Collections newSetFromMap Backed By Map

Collections.newSetFromMap turns any empty Map into a Set, inheriting the map ordering and concurrency: with a LinkedHashMap you get insertion-ordered sets.

JavaData Integrity

Code

snippet
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapBackedSets {

    public static void main(String[] args) {
        // LinkedHashMap 支撑的 set:迭代按插入顺序
        Set<String> insertionOrdered =
                Collections.newSetFromMap(new LinkedHashMap<>());
        insertionOrdered.add("parse");
        insertionOrdered.add("validate");
        insertionOrdered.add("execute");
        System.out.println("ordered set: " + insertionOrdered);

        // 重复 add 返回 false,set 语义来自 map 的 put
        System.out.println("re-add: " + insertionOrdered.add("parse"));
        System.out.println("size stays: " + insertionOrdered.size());

        // TreeMap 支撑的 set:天然有序
        Set<String> sorted = Collections.newSetFromMap(new TreeMap<>());
        sorted.add("delta");
        sorted.add("alpha");
        sorted.add("charlie");
        System.out.println("sorted set:  " + sorted);

        // addAll 在底层是逐个 put
        insertionOrdered.addAll(Set.of("execute", "report"));
        System.out.println("after addAll: " + insertionOrdered);
    }
}

How the snippet works

The snippet is organized around the class MapBackedSets and the function main.

What to watch for

  • Imports, when present, point only at standard-library modules.

Applying it

The signature doing the main work is public static void main(String[] args)

The run emits 5 labeled sections — ordered set:, re-add:, size stays:, sorted set:, after addAll: — one per step.

Statements that decide the outcome

Set<String> sorted = Collections.newSetFromMap(new TreeMap<>());
insertionOrdered.addAll(Set.of("execute", "report"));
Collections.newSetFromMap(new LinkedHashMap<>());

Interactive Tools for This Topic

FAQ

What does Collections newSetFromMap Backed By Map print when run?
Execute the whole file; each printed line is prefixed with a label like `ordered set:`, `re-add:`, `size stays:`.