How to iterate hashmap in reverse order in Java
hashmap, java
Solution
Hashmap does not have specific order. But you can use TreeMap.
Perhaps this simple example can help you :
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "abc1");
map.put(2, "abc2");
map.put(3, "abc3");
ArrayList<Integer> keys = new ArrayList<Integer>(map.keySet());
for(int i=keys.size()-1; i>=0;i--){
System.out.println(map.get(keys.get(i)));
}
Problem
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<Integer, List<String>> map = new HashMap<Integer, List<String>>(); for(Integer key : map.keySet()) { 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 })); } ``` I have seen example of TreeMap as well, ``` Map<Integer, List<String>> sortedMap = new TreeMap<Integer, List<String>>(map); ``` But treemap also gives in ascending order, what I want is in descending order.