简体   繁体   English

Java 用集合中的键初始化 map

[英]Java initialize map with keys from set

In java, can you initialize a new map's keyset based on the values of an existing set?在 java 中,您可以根据现有集合的值初始化新地图的键集吗?

Something like:就像是:

Set<String> setOfStrings = getSetFromSomeOtherFuntion();

Map<String, Boolean> map = new Hashmap<>(setOfStrings);

If that's possible, then I would presume the value for each entry in the map is null, which is ok, but even better would be if a default value could be set (for example, false if it's Boolean).如果这是可能的,那么我会假设 map 中每个条目的值是 null,这没关系,但如果可以设置默认值(例如,如果它是布尔值则为 false)更好。

Map<K, V> map = new HashMap<>();

setOfStrings.forEach(e -> map.put(e, false));

You can use stream with Collectors.toMap like so:您可以将 stream 与Collectors.toMap一起使用,如下所示:

Map<String, Boolean> map = setOfStrings.stream()
        .collect(Collectors.toMap(Function.identity(), v -> false));

If you have to do it in the constructor, you could do something like this:如果您必须在构造函数中执行此操作,则可以执行以下操作:

Set<String> set = new HashSet<String>();
set.add("Key1");
set.add("Key2");
set.add("Key3");

Map<String, Boolean> map = new HashMap<String, Boolean>() {
    {
        set.forEach(str -> put(str, false));
    }
};

System.out.println(map);

Output: Output:

{Key2=false, Key1=false, Key3=false}

However, this method is a little dirty and honestly unnecessary.但是,这种方法有点脏,老实说没有必要。 You might want to see Efficiency of Java "Double Brace Initialization"?您可能想查看Java“双大括号初始化”的效率?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM