Collections public static Set newSetFromMap(Map map) method Example program


Returns a set backed by the specified map.

Program

package com.candidjava;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.newSetFromMap(Map <E, Boolean > map) method.
 */
public class CollectionsNewSetFromMap {
	public static void main(String args[]) {
		Map<String, Boolean> map = new WeakHashMap<String, Boolean>();
		Set<String> set = Collections.newSetFromMap(map);
		set.add("Karthik");
		set.add("mohan");
		set.add("kamal");
		set.add("anandh");
		set.add("hari");
		System.out.println("Set is: " + set);
		System.out.println("Map is: " + map);
	}
}

Output

Set is: [mohan, kamal, Karthik, hari, anandh]
Map is: {mohan=true, kamal=true, Karthik=true, hari=true, anandh=true}

Explanation

public static <E> Set<E> newSetFromMap(Map<E,Boolean> map)
Returns 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).
Each method invocation on the set returned by this method results in exactly one method invocation on the backing map or its keySet view, with one exception. The addAll method is implemented as a sequence of put invocations on the backing map.

The specified map must be empty at the time this method is invoked, and should not be accessed directly after this method returns. These conditions are ensured if the map is created empty, passed directly to this method, and no reference to the map is retained, as illustrated in the following code fragment:

    Set<Object> weakHashSet = Collections.newSetFromMap(
        new WeakHashMap<Object, Boolean>());
 
Parameters:
map - the backing map
Returns:
the set backed by the map
Throws:
IllegalArgumentException - if map is not empty
Since:
1.6


Related Post

Comments


©candidjava.com