Collections newSetFromMap() method in Java with Examples
Last Updated :
25 Oct, 2019
The newSetFromMap() method of java.util.Collections class is used to return a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides a Set implementation corresponding to any Map implementation. There is no need to use this method on a Map implementation that already has a corresponding Set implementation (such as HashMap or TreeMap).
Syntax:
public static Set newSetFromMap(Map map)
Parameters: This method takes the backing map as a parameter
Return Value: This method returns the set backed by the map
Exception: This method throws IllegalArgumentException, if map is not empty.
Below are the examples to illustrate the newSetFromMap() method
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Map<String, Boolean>
map = new WeakHashMap<String, Boolean>();
Set<String> set = Collections.newSetFromMap(map);
set.add( "A" );
set.add( "B" );
set.add( "C" );
set.add( "D" );
System.out.println( "Map is: " + map);
System.out.println( "Set from Map is: " + set);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Map is: {C=true, B=true, A=true, D=true}
Set from Map is: [C, B, A, D]
Example 2: for IllegalArgumentException
import java.util.*;
<div class = 'outputDiv' >
<b>Output:</b>
<pre>
Set is: [C, B, A, D]
Map is: {C= true , B= true , A= true , D= true }
</pre>
</div>
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
Map<String, Boolean>
map = new WeakHashMap<String, Boolean>();
map.put( "1" , true );
Set<String> set = Collections.newSetFromMap(map);
set.add( "A" );
set.add( "B" );
set.add( "C" );
set.add( "D" );
System.out.println( "Map is: " + map);
System.out.println( "Set from Map is: " + set);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Exception thrown : java.lang.IllegalArgumentException: Map is non-empty
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...