Java:在哈希表keySet上反转迭代的顺序.怎么样?

Sef*_*an2 3 java hashtable

我正在迭代一个哈希表,连接字符串值:

    Iterator<String> it = jsonHashtableTemp.keySet().iterator();
    String json = new String("[");
    while (it.hasNext()) {
        String s = it.next();
        json = json.concat(jsonHashtableTemp.get(s).toString());
        if (it.hasNext()) {
             json = json.concat(", ");
        }
    }
    json = json.concat("]");
Run Code Online (Sandbox Code Playgroud)

我想颠倒迭代的顺序.

可能吗?

Jac*_*obi 9

您也可以使用"Collections.reverse()"函数进行反转.按照Francisco Spaeth的例子,

List<String> list = new ArrayList<String>(jsonHashTableTemp.keySet());

Collections.reverse(list);

for (String value : list) {
   jsonHashTableTemp.get(value);
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*eth 5

您无法使用它Iterator,但您可以将其添加到列表中并使用简单的方法迭代它,如下所示:

List<String> l = new ArrayList<String>(jsonHashTableTemp.keySet());
for (int i = l.size()-1; i >= 0; i--) {
   jsonHashTableTemp.get(l.get(i));
}
Run Code Online (Sandbox Code Playgroud)

这是有道理的,以防你使用一些有序的哈希,就像LinkedHashMap已经评论过的那样.

编辑:纠正l.get(i)内部循环