java.util.Collections.newSetFromMap() Method


Advertisements


Description

The newSetFromMap(Map<, Boolean>) method is used to return a set backed by the specified map.

Declaration

Following is the declaration for java.util.Collections.newSetFromMap() method.

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

Parameters

  • map -- The backing map

Return Value

The method call returns the set backed by the map.

Exception

  • IllegalArgumentException -- This is thrown if map is not empty.

Example

The following example shows the usage of java.util.Collections.newSetFromMap()

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String args[]) { 
   // create map
   Map<String, Boolean> map = new WeakHashMap<String, Boolean>();

   // create a set from map
   Set<String> set = Collections.newSetFromMap(map); 
      
   // add values in set
   set.add("Java"); 
   set.add("C");
   set.add("C++");
      
   // set and map values are
   System.out.println("Set is: " + set);
   System.out.println("Map is: " + map);
   }
}	

Let us compile and run the above program, this will produce the following result.

Set is: [Java, C++, C]
Map is: {Java=true, C++=true, C=true}

java_util_collections.htm

Advertisements