Java Utility Library

Java Collections - newSetFromMap() Method



The java.util.Collections.newSetFromMap() method returns a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map.

Syntax

public static <E> Set<E> newSetFromMap(Map<E,
                                       Boolean> map)

Here, E is the type of map keys and elements in the set.


Parameters

map Specify the backing map.

Return Value

Returns the set backed by the map.

Exception

Throws IllegalArgumentException, if map is not empty

Example:

In the example below, the java.util.Collections.newSetFromMap() method is used to get a set backed by the specified map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating map object
    Map<Integer, Boolean> MyMap = new HashMap<Integer, Boolean>();

    //create a set from map
    Set<Integer> MySet = Collections.newSetFromMap(MyMap);

    //populating the set
    MySet.add(101);
    MySet.add(102);
    MySet.add(103);

    //printing the set
    System.out.println("MySet contains: " + MySet); 

    //printing the map
    System.out.println("MyMap contains: " + MyMap); 
  }
}

The output of the above code will be:

MySet contains: [101, 102, 103]
MyMap contains: {101=true, 102=true, 103=true}

❮ Java.util - Collections