I am trying this for some hour but not finding any best approach to achieve iteration of hashmap in reverse order, this is the hashmap I have.
Map
Perhaps you need a NavigableMap, like a TreeMap.
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "abc1");
map.put(2, "abc2");
map.put(3, "abc3");
NavigableMap<Integer, String> nmap = map.descendingMap();
for (NavigableMap.Entry<Integer, String> entry : nmap.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
An implementation of NPE idea.
But treemap also gives in asecding order, what i want is in descending order.
Implement a Comparator
that will compare it reverse than natural order and then just iterate normally you will have reverse iteration
I've found that the Iterators obtained from Java Hashtable via: Hashtable.values().iterator() and Hashtable.keys().asIterator() are both in reverse order by default. One oddity, The values().iterator has a first final value of "0" which I didn't add when populating it.
Use insted:
new TreeMap<>(Collections.reverseOrder())
and you will get what you want.
You can use TreeMap#descendingKeySet
method.
Map<Integer, List<String>> map = new TreeMap<Integer, List<String>>();
for(Integer key : map.descendingKeySet()) {
List<String> value = map.get(key);
List<Map<String,?>> security = new LinkedList<Map<String,?>>();
for(int ixy = 0; ixy < value.size()-1; ixy++){
security.add(createItem(value.get(ixy), value.get(ixy+1)));
}
adapter.addSection(Integer.toString(key), new SimpleAdapter(getApplicationContext(), security, R.layout.list_complex, new String[] { ITEM_TITLE, ITEM_CAPTION }, new int[] { R.id.list_complex_title, R.id.list_complex_caption }));
}
Reference:
https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#descendingKeySet--