3

I'm iterating on an hashtable, concatenating the string values:

    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("]");

I would to reverse the order of the iteration .

Is it possible?

Sefran2
  • 3,578
  • 13
  • 71
  • 106
  • 11
    Unless you're using `LinkedHashMap`, you're not going to get a predicable iteration order in the first place, so reversing it won't do you much good. – beerbajay Jun 19 '12 at 08:56
  • Put the keySet into a new ArrayList and then iterate through that backwards. – Thilo Jun 19 '12 at 08:57

3 Answers3

10

You can reverse, using the "Collections.reverse()" function too. Following the Francisco Spaeth's example,

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

Collections.reverse(list);

for (String value : list) {
   jsonHashTableTemp.get(value);
}
Community
  • 1
  • 1
Jacobi
  • 1,508
  • 15
  • 29
5

You are not able to do it using Iterator, but you could add it to a list and iterate it with a simple for like this:

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

And this makes sense just in case you are using some ordered Hash like LinkedHashMap as already commented.

EDIT: corrected the l.get(i) inside loop

hidralisk
  • 706
  • 6
  • 18
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
1

If you are using Hashtable or HashMap the order is not guarantied at all. It might be different from run to run. You should use LinkedHashMap or TreeMap if you want to iterate on insertion order or on natural order, respectively. Only then you could use the already suggested approach of copying the keySet() into an ArrayList and iterating backwards.

Note: You should use the StringBuilder instead of concatenating strings. Otherwise you will see a performance hit with a large data set.

StringBuilder jsonSB = new StringBuilder();
jsonSB.append("[");
List<String> l = new ArrayList<String>(jsonHashTableTemp.keySet());
for (int i = l.size() - 1; i >= 0; i--) {
    jsonSB.append(jsonHashTableTemp.get(l.get(i)));
    jsonSB.append(", ");
}
jsonSB.append("]");
String json = jsonSB.toString();
hidralisk
  • 706
  • 6
  • 18