Java教程

Java Collections newSetFromMap()

Java集合类的 newSetFromMap()方法用于返回由指定地图支持的集合。结果集显示的排序,并发性和性能特征与支持映射相同。

语法

以下是 newSetFromMap()方法的声明:
public static <E> Set<E> newSetFromMap(Map<E,Boolean> map)

参数

参数 说明 必需/可选
map 这是背景图。 必需

返回

newSetFromMap()方法返回由指定地图支持的集合。

异常

IllegalArgumentException -如果映射不为空,则抛出此异常。

兼容版本

Java 1.6及更高版本

示例1

import java.util.*;
public class CollectionsNewSetFromMapExample1 {
    public static void main(String[] args) {      
        // create map
          Map<String, Boolean> map = new WeakHashMap<String, Boolean>();
          // create a set from map
          Set<String> set = Collections.newSetFromMap</span>(map); 
          // add values in set
          set.add("Raj"); 
          set.add("Rahul");
          set.add("Karan");
          // set and map values are
          System.out.println("Set is: " + set);
          System.out.println("Map is: " + map);
          }
}
输出:
Set is: [Karan, Raj, Rahul]
Map is: {Karan=true, Raj=true, Rahul=true}

示例2

import java.util.*;
public class CollectionsNewSetFromMapExample2 {
    public static void main(String[] args) {      
        Map<Integer, Boolean> map = new IdentityHashMap<Integer, Boolean>();
          Set<Integer> set = Collections.newSetFromMap</span>(map);
          set.add(1);
          set.add(1);
          set.add(1);
          // set and map values are
        System.out.println("Set is: " + set);
        System.out.println("Map is: " + map);
          }
}
输出:
Set is: [1]
Map is: {1=true}

示例3

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class CollectionsNewSetFromMapExample3 {
    public static void main(String[] args) {      
        Set<String> users = Collections.newSetFromMap</span>(new ConcurrentHashMap<String, Boolean>());
            System.out.println("Users: " + users);
            users.add("Java");
            users.add("PHP");
            System.out.println("Users: " + users);
          }
}
输出:
Users: []
Users: [Java, PHP]

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4