简体   繁体   English

迭代HashMap <String, List<Class> &gt;

[英]Iterate over HashMap<String, List<Class>>

how would i iterate over the list "values" that one string "key" has. 我将如何迭代一个字符串“key”具有的列表“值”。

Map<String, List<wordsStreamed>> hm = new HashMap<String, List<wordsStreamed>>();
hm.put(wordChoosen, sw.streamMethod());

hm has one key and over 10,000 values. hm有一个密钥和超过10,000个值。 i want to iterate over the values so i can compare my key with all the values. 我想迭代值,以便我可以将我的键与所有值进行比较。 also i would like to know if this code is the best way to get my String values from the list of classes. 另外我想知道这段代码是否是从类列表中获取String值的最佳方法。

hm.values().iterator().next().get(i).toString()

To iterate over your HashMap 's values, you can use fast-enumeration. 要迭代HashMap的值,可以使用快速枚举。

What you probably need here is to iterate over the key set, then access the List for each value and iterate over each of the List 's items to compare it to the key. 你可能需要的是遍历密钥集,然后访问每个值的List并迭代每个List的项目以将其与密钥进行比较。

For instance: 例如:

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()));
            }
        }
    }
}

Note I've replaced your WordsStreamed class here with the Object class. 注意我已经用Object类替换了你的WordsStreamed类。

i want to iterate over the values so i can compare my key with all the value 我想迭代值,以便我可以将我的密钥与所有值进行比较

looks like misuse of data structure , generally you should not have to iterate in such scenario and values should be mapped with key 看起来像是滥用数据结构,通常你不应该在这种情况下迭代,值应该用key映射

you should enter the values those are logically mapped with keys so while retrieving you won't have to iterate through all they keys and associated values 你应该输入那些用键逻辑映射的值,这样在检索时你不必遍历它们所有的键和相关的值。

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

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