字符串作为Hashmap中的关键字

时间:2016-06-06 11:38:25

标签: java string hashmap

我是Java的新手 是否可以将String或String []转换为Hashmap的键? 我的意思是:

String keysToConvert = "key1,key2,key3";

HashMap<String, Double> hashmap = new HashMap<String, Double>();
[apply in some way the keys of the string]
hashmap.get("key2");

我知道hashmap.get("key2");目前没有任何价值。我只想知道是否有办法在HashMap中加载密钥。

2 个答案:

答案 0 :(得分:3)

hashmap.put("key2", 1.0d);
System.out.println(hashmap.get("key2")); // prints 1.0

这是Map

的基本用法

答案 1 :(得分:1)

如果你有String [],你可以使用for-each循环添加它们:

String[] keys = {"key1", "key2", "key3"};
HashMap<String, Double> hashmap = new HashMap<String, Double>();

for (String key : keys) {
    hashmap.put(key, null);
}