Collections.newSetFromMap(Map): This method is available in java.util.Collections class of Java.
Syntax:
<E> Set<E> java.util.Collections.newSetFromMap(Map<E, Boolean> map)
This method takes one argument. This method returns a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map.
Parameters: One parameter is required for this method.
map: the backing map.
Returns: the set backed by the map.
Throws:
1. IllegalArgumentException - if map is not empty.
Approach 1: When no exception
Java
import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.Set;public class CollectionsnewSetFromMap {public static void main(String[] args) {Map<Integer, Boolean> map = new HashMap<Integer,Boolean>();Set<Integer> set = Collections.newSetFromMap(map);set.add(10);set.add(20);set.add(6);System.out.println(map);}}
Output:
{20=true, 6=true, 10=true}
Approach 2: IllegalArgumentException
Java
import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.Set;public class CollectionsnewSetFromMap {public static void main(String[] args) {Map<Integer, Boolean> map = new HashMap<Integer,Boolean>();map.put(8, true);Set<Integer> set = Collections.newSetFromMap(map);set.add(10);set.add(20);set.add(6);System.out.println(map);}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Map is non-empty at java.base/java.util.Collections$SetFromMap.<init>(Collections.java:5644) at java.base/java.util.Collections.newSetFromMap(Collections.java:5629)
No comments:
Post a Comment