我如何迭代一个字符串“key”所具有的列表“值”。
Map<String, List<wordsStreamed>> hm = new HashMap<String, List<wordsStreamed>>();
hm.put(wordChoosen, sw.streamMethod());
hm 有一个键和超过 10,000 个值。我想迭代这些值,以便可以将我的 key 与所有值进行比较。我也想知道这段代码是否是从类列表中获取字符串值的最佳方法。
hm.values().iterator().next().get(i).toString()
最佳答案
要迭代 HashMap
的值,您可以使用快速枚举。
这里您可能需要迭代键集,然后访问每个值的 List
并迭代 List
的每个项目以进行比较到关键。
例如:
Map<String, List<Object>> hm = new HashMap<String, List<Object>>();
for (String key : hm.keySet()) {
// gets the value
List<Object> value = hm.get(key);
// checks for null value
if (value != null) {
// iterates over String elements of value
for (Object element : value) {
// checks for null
if (element != null) {
// prints whether the key is equal to the String
// representation of that List's element
System.out.println(key.equals(element.toString()));
}
}
}
}
注意我已将此处的 WordsStreamed
类替换为 Object
类。
关于java - 迭代 HashMap<String, List<Class>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19432850/