Java Collections newSetFromMap() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 6+

Definition

In Java, Collections.newSetFromMap(map) returns a Set whose elements are stored as the keys of map (every value is Boolean.TRUE). The set behaves exactly like the map does: same ordering, same thread-safety, same rules about null.

It exists for maps that have no matching Set class, the classic case being ConcurrentHashMap, which gives you a thread-safe hash set.

A static method of the java.util.Collections utility class, available since Java 6. Call it on the class name, as in Collections.newSetFromMap(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Pass a new, empty map with Boolean values.

Java
Set<String> safe = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
Set<String> ordered = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>());
CallWhat it does
newSetFromMap(new ConcurrentHashMap<>())Thread-safe set with weakly consistent iteration.
newSetFromMap(new LinkedHashMap<>())Insertion-ordered set (like LinkedHashSet).
newSetFromMap(new WeakHashMap<>())Set whose elements can be garbage-collected.
ConcurrentHashMap.newKeySet()Java 8+ shortcut for a concurrent set.

Added in Java 6. Since Java 8, ConcurrentHashMap.newKeySet() is a shorter way to get a concurrent set, but newSetFromMap works with any map type.

Library declarations
Java
// java.util.Collections
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map)

Parameters

ParameterDescription
mapAn empty map that will hold the set's elements as keys. Do not use it directly afterwards.

Return Value

Return ValueDescription
Set<E>A set backed by map.

Compare with Similar Methods

Other ways to get special sets:

MethodHow it differs
synchronizedSet(s)Thread-safe by locking every call.
unmodifiableSet(s)Read-only view of a set.
asLifoQueue(d)Another adapter: a LIFO Queue view of a Deque.

Java Examples

Example 1 — An Insertion-Ordered Set from LinkedHashMap

Add words with a duplicate and watch both the set and its backing map.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class CollectionsNewSetFromMapOrdered {
    public static void main(String[] args) {
        Map<String, Boolean> backing = new LinkedHashMap<>();
        Set<String> seen = Collections.newSetFromMap(backing);

        for (String s : Arrays.asList("banana", "apple", "banana", "cherry")) {
            System.out.println("add " + s + ": " + seen.add(s));
        }
        System.out.println("set: " + seen);
        System.out.println("map: " + backing);
    }
}

How It Works

  1. add = put. Each add puts the word into the map with value true and reports whether the key was new.
  2. Duplicate rejected. The second "banana" is already a key, so add returns false.
  3. Map decides order. LinkedHashMap keeps insertion order, so the set prints banana, apple, cherry, and the map shows every value as true.

Example 2 — A ConcurrentHashMap-Backed Set

Remove items while looping over the set (which would fail on a HashSet), then try to add null.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

public class CollectionsNewSetFromMapConcurrent {
    public static void main(String[] args) {
        Set<String> online = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
        online.addAll(Arrays.asList("ana", "tmp1", "bo", "tmp2"));

        for (String user : online) {
            if (user.startsWith("tmp")) {
                online.remove(user);
            }
        }
        System.out.println("left: " + new TreeSet<>(online) + " size " + online.size());

        try {
            online.add(null);
        } catch (NullPointerException e) {
            System.out.println("add(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Weakly consistent iteration. ConcurrentHashMap iterators never throw ConcurrentModificationException, so removing during the loop is safe.
  2. Stable printing. Hash order is not predictable, so the code prints a sorted TreeSet copy: the two temporary users are gone.
  3. Map rules apply. ConcurrentHashMap forbids null keys, so the set's add(null) throws NullPointerException.

Example 3 — The Map Must Start Empty

Pass a non-empty map, then build a descending set from a TreeMap with a reverse comparator.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class CollectionsNewSetFromMapRules {
    public static void main(String[] args) {
        Map<String, Boolean> used = new TreeMap<>();
        used.put("x", true);
        try {
            Collections.newSetFromMap(used);
        } catch (IllegalArgumentException e) {
            System.out.println("non-empty map: " + e.getClass().getSimpleName());
        }

        Map<String, Boolean> desc = new TreeMap<String, Boolean>(Collections.<String>reverseOrder());
        Set<String> letters = Collections.newSetFromMap(desc);
        letters.addAll(Arrays.asList("b", "c", "a"));
        System.out.println("descending set: " + letters);
    }
}

How It Works

  1. Guard. The map already holds "x", so newSetFromMap refuses it with IllegalArgumentException.
  2. Any map works. A TreeMap built with reverseOrder() is empty and accepted.
  3. Ordering inherited. The letters are stored as tree keys, so the set iterates in descending order: c, b, a.

Frequently Asked Questions

It returns a Set that stores its elements as the keys of the map you pass, so the set gets that map's ordering and concurrency behavior.
The map you pass must be empty. A map that already has entries is rejected.
Collections.newSetFromMap(new ConcurrentHashMap<>()) works since Java 6; ConcurrentHashMap.newKeySet() is a Java 8+ shortcut.
You should not. Treat the map as the set's internal storage and make all changes through the set.
Java 6.

Next: replaceAll()

Replace every occurrence of one value with another.

replaceAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful