3

I have Map<String, List<String>> map now, putting two values inside Map, now when read keyset from map gives in different sequence in different device.

private Map<String, List<String>>  map = new HashMap<>();

map.put("First", new ArrayList<String>());
map.put("Second", new ArrayList<String>());

Now, Read keys from this map.

 Set<String> keys = map.keySet();

 for (int i = 0; i < map.size(); i++) {
     Log.d("key", keys.toArray()[i].toString());
 }

OUTPUT IN OREO 8.0

D/Key : First
D/Key : Second

OUTPUT in BELOW 8.0

D/Key : Second
D/Key : First
Vishal Patoliya ツ
  • 3,170
  • 4
  • 24
  • 45

3 Answers3

1

I got a solution until we defined Set as SortedSet ,we getting key sequence in different order.

SortedSet<String> keys =  new TreeSet<>(map.keySet());

for (int i = 0; i < map.size(); i++) {
    Log.d("key", keys.toArray()[i].toString());            
}
Vishal Patoliya ツ
  • 3,170
  • 4
  • 24
  • 45
1

You're using the HashMap as the data structure. As in HashMap, the order of insertion is not maintained thus you're getting a random order of the keys. If you want to maintain the order of insertion, simply use a LinkedHashMap. The order in which you put the data is maintained and simply you can iterate over it.

Sample code for LinkedHashMap:

Map<String, String> map = new LinkedHashMap<>();
    map.put("key1", "value2");
    map.put("key3", "value4");
    map.put("key5", "value6");
    map.put("key7", "value8");
    Set<String> keySet = map.keySet();
    for(String st: keySet){
        System.out.println(st);
    }
    for(Map.Entry<String, String> entry : map.entrySet()){
        System.out.println(entry.getKey() + " " + entry.getValue());
    }

Output:

key1
key3
key5
key7
key1 value2
key3 value4
key5 value6
key7 value8
mark42inbound
  • 364
  • 1
  • 4
  • 19
0

It has nothing to do with the android OS. The resulting Set of HashMap has no order. However there are Sets with an order e.g. TreeSet.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107