-2

Hello there Stack overflowers I have problem with my hashmap foreach order in android. i have:

    hm = new HashMap<>();
    hm.put("aaaa","aaaa");
    hm.put("bbbb","bbbb");
    hm.put("cccc","cccc");
    return hm;

and now i do foreach of this hashmap :

for(Map.Entry<String, String> entry : hashmap.entrySet()){
        try{
            String key = entry.getKey();
            String value = entry.getValue();

            Toast.makeText(getActivity(),key+" "+ value + " "+,Toast.LENGTH_LONG).show();
        }catch (Exception e){

        }
    }

And it toast me in reverse order so :cccc cccc , bbbb bbbb, aaaa aaaa. What i must do to have my toast in good oreder ? Greetings

Juri Bojka
  • 305
  • 2
  • 8
  • 18

1 Answers1

1

if you want the key in sorted order use TreeMap

TreeMap<String, String> hm = new TreeMap<>();
hm.put("aaaa", "aaaa");
hm.put("bbbb", "bbbb");
hm.put("cccc", "cccc");
for (String key : hm.keySet()) {
    System.out.println(key + "  " + hm.get(key));
}
Ashraful Islam
  • 12,470
  • 3
  • 32
  • 53