如何使用两个迭代器迭代HashMap?

sam*_*ell 3 java hashmap map

我想在HashMap中搜索重复项.目前这是我的HashMap:

HashMap<String, HashMap<String, String>>

我打算创建两个迭代器,一个i和另一个j,以及两个循环.第一while循环将具有的索引i,然后第二环路将具有的索引j,但j==i在循环开始之前.

Iterator<Entry<String, HashMap<String, String>>> i = listings.entrySet().iterator();
while(i.hasNext()) {
    HashMap<String, String> entry = i.next().getValue();
    Iterator<Entry<String, HashMap<String, String>>> j = i;

    while(j.hasNext()) {
        j.next();
        // DO STUFF
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为当我打电话时j.next(),它也会改变索引i.

ajb*_*ajb 6

它看起来你想要一个穿过整个映射的迭代器,并且对于每次迭代,你想要另一个迭代器穿过映射的PART,从第一个迭代器当前指向的位置开始.Java无法设置从中间开始的迭代器.此外,我不认为迭代器将以特定顺序通过; 因此,如果您尝试创建一个新的迭代器,然后只是跳过前N来达到您想要的点,我就不会指望它能够工作.

您可能想尝试将Map.Entry对象集转换为数组:

Set <Map.Entry<String, HashMap<String, String>>> entrySet =
        listings.entrySet();
Map.Entry<String, HashMap<String, String>>[] entryArr =
    (Map.Entry<String, HashMap<String, String>>[])
        entrySet.toArray ();

for (int i = 0; i < arr.length; i++) {
    for (int j = i; j < arr.length; j++) {
         // something
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,当你使用toArray()时,这会给出关于未经检查的操作的警告,但我不知道如何解决这个问题.

编辑:按照Louis Wasserman的建议(谢谢!):

Set <Map.Entry<String, HashMap<String, String>>> entrySet =
        listings.entrySet();
ArrayList<Map.Entry<String, HashMap<String, String>>> entryArr =
    new ArrayList<Map.Entry<String, HashMap<String, String>>> (entrySet);

for (int i = 0; i < arr.size(); i++) {
    for (int j = i; j < arr.size(); j++) {
         // something; use arr.get(i), arr.get(j) to get at the keys/values
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能是最好的方法,但不是使用`toArray`,而是使用`new ArrayList <Map.Entry <String,HashMap <String,String >>>(listings.entrySet())`并使用`ArrayList `而不是数组. (2认同)