使用HashSet作为值迭代HashMap

时间:2014-08-22 07:54:43

标签: java hashmap hashset

我有HashMap和HashSet作为值 如何迭代它重复结果如:

   key1
   value1
   value2
   value3
   ...
   key2
   value1
   value2
   value3
   key3
   ...

我的代码中出了点问题:

Map<String, HashSet<String>> remarksMap = new HashMap<String, HashSet<String>>();
//...

Iterator<Map.Entry<String, HashSet<String>>> itr1 = remarksMap.entrySet().iterator();
Iterator<String> itr2 = itr1.next().getValue().iterator();

    while (itr1.hasNext()) {

        System.out.println(itr1.next().getKey());

        while (itr2.hasNext()) {
            System.out.println(itr2.next());

        }
    }

目前收到的错误结果如下:

key1
value1
value2
value3
key2
key3
key4
...

5 个答案:

答案 0 :(得分:2)

您不需要显式Iterator来执行此操作。

这是一个带有快速枚举的简化嵌套迭代:

Map<String, HashSet<String>> remarksMap = new HashMap<String, HashSet<String>>();
for (String k: remarksMap.keySet()) {
    System.out.printf("%s%n", k);
    for (String v: remarksMap.get(k)) {
        System.out.printf("\t%s%n", v);
    }
}

答案 1 :(得分:1)

Iterator<String> itr2 = itr1.next().getValue().iterator();放入你的循环中:

Map<String, HashSet<String>> remarksMap = new HashMap<String, HashSet<String>>();
//...

Iterator<Map.Entry<String, HashSet<String>>> itr1 = remarksMap.entrySet().iterator();

while (itr1.hasNext()) {

    Map.Entry<String, HashSet<String>> entry = itr1.next();
    System.out.println(entry R.getKey());
    Iterator<String> itr2 = entry .getValue().iterator();

    while (itr2.hasNext()) {
        System.out.println(itr2.next());

    }
}

答案 2 :(得分:1)

使用地图的第一个元素的值初始化itr2,而不是使用当前元素的值。像

一样调整它
Iterator<Map.Entry<String, HashSet<String>>> itr1 = remarksMap.entrySet().iterator();

while (itr1.hasNext()) {
    Map.Entry<String, HashSet<String>> entry = itr1.next();
    System.out.println(entry.getKey());
    Iterator<String> itr2 = entry.getValue().iterator();

    while (itr2.hasNext()) {
        System.out.println(itr2.next());
    }
}

答案 3 :(得分:0)

itr2作业移至itr1 while圈内。

但要小心!外部循环中的System.out.println()抓取下一个密钥,您的itr2分配目前也是如此。确保每次循环时只调用next(),否则你会错过一些密钥。

答案 4 :(得分:0)

检查以下代码,

    Map<String,HashSet<String>> map = new HashMap<String,HashSet<String>>(); // Map with HashSet as value

    HashSet<String> hashset1 = new HashSet<String>();
    hashset1.add("Midhun");
    hashset1.add("Amal");
    hashset1.add("Ajith");

    HashSet<String> hashset2 = new HashSet<String>();
    hashset2.add("Sooraj");
    hashset2.add("Vinay");
    hashset2.add("Vishnu");

    // Putting data in to Map
    map.put("friends",hashset1);
    map.put("relatives",hashset2);

    for(Entry<String,HashSet<String>> mapEntry : map.entrySet()){
        System.out.println("Key :: "+mapEntry.getKey());
        for(String value : mapEntry.getValue()){
            System.out.println("Value :"+value);
        }
        System.out.println("===================");
    }