Collections.newSetFromMap ​

java.util.Collections类中:

   /**
     * 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 {@link Set}
     * implementation corresponding to any {@link Map} implementation.  There
     * is no need to use this method on a {@link Map} implementation that
     * already has a corresponding {@link Set} implementation (such as {@link
     * HashMap} or {@link TreeMap}).
     *
     * <p>Each method invocation on the set returned by this method results in
     * exactly one method invocation on the backing map or its {@code keySet}
     * view, with one exception.  The {@code addAll} method is implemented
     * as a sequence of {@code put} invocations on the backing map.
     *
     * <p>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:
     * <pre>
     *    Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
     *        new WeakHashMap&lt;Object, Boolean&gt;());
     * </pre>
     *
     * @param <E> the class of the map keys and of the objects in the
     *        returned set
     * @param map the backing map
     * @return the set backed by the map
     * @throws IllegalArgumentException if {@code map} is not empty
     * @since 1.6
     */
    public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
        return new SetFromMap<>(map);
    }

需要注意上面中的

eturns a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map.

一个使用例子:


import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        LinkedHashMap<String, Boolean> map = new LinkedHashMap<>();
        Set<String> strings = Collections.newSetFromMap(map);
        strings.add("1");
        strings.add("2");
        System.out.println(map);
        System.out.println(strings);

        strings.add("1");
        strings.add("3");
        System.out.println(map);
        System.out.println(strings);

        strings.remove("3");
        System.out.println(map);
        System.out.println(strings);

        //输出为
        //{1=true, 2=true}
        //[1, 2]
        //{1=true, 2=true, 3=true}
        //[1, 2, 3]
        //{1=true, 2=true}
        //[1, 2]
    }
}
本文版权归作者所有,禁止一切形式的转载,复制等操作
赞赏

微信赞赏支付宝赞赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注