Example of Collections.newSetFromMap in Java
May 26, 2013
In Java, Collections.newSetFromMap returns a Set backed by provided Map. If we add elements in resulting Set, the backing map will also be populated with that element automatically. If we add element in Map, element will also be added in Set automatically. While using Collections.newSetFromMap() we need to provide an empty Map. The Map which already provides Set implementation like TreeMap or HashMap should not to be used with Collections.newSetFromMap. We can use WeakHashMap. Find the example.
CollectionsNewSetFromMap.java
package com.concretepage.util; import java.util.Collections; import java.util.Set; import java.util.WeakHashMap; public class CollectionsNewSetFromMapDemo { public static void main(String[] args) { WeakHashMap<String, Boolean> weakHashMap = new WeakHashMap<>(); //Use empty WeakHashMap Set<String> set = Collections.newSetFromMap(weakHashMap); //add values in WeakHashMap weakHashMap.put("AAAA", true); weakHashMap.put("BBBB", false); weakHashMap.put("CCCC", true); //add values in Set set.add("DDDD"); set.add("EEEE"); //print Set System.out.println(set); //print WeakHashMap System.out.println(weakHashMap); } }
[CCCC, EEEE, BBBB, DDDD, AAAA] {CCCC=true, EEEE=true, BBBB=false, DDDD=true, AAAA=true}