Java Programming Tutorials

Java programming tutorials with many code examples!

Java Collections newSetFromMap


In Java some Map implementations have corresponding Sets, but not all of them. How to create a Set with the same ordering, concurrency, and performance characteristics?


The solution for that problem is hidden in Java Collections API. Not many people know about method java.util.Collections.newSetFromMap(Map<E,Boolean>) that returns a Set with the same characteristics (ordering, concurrency, performance) as given map.

Here’s an example, where we create a ConcurrentSet out of ConcurrentHashMap:


import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class CollectionsNewSetFromMap {

    public static void main(String[] args) {
        Set<String> users = Collections.newSetFromMap(
                new ConcurrentHashMap<String, Boolean>());

        System.out.println("Users: " + users);


        System.out.println("Users: " + users);

The new set is concurrent, because the map used for its construction is concurrent and the map is used as implementation of the set.

There are two important things about Map:

  1. Has to be empty, else IllegalArgumentException will be thrown.
  2. Should not be accessed from outside of the Set, after its creation.

Running the example gives:

Users: []
Users: [Tyron, Jon]

The method newSetFromMap(Map) is really cool, but not known to many. :-)

Was it helpful? Share!