javaandroidhashmapandroid-8.0-oreokeyset

Map.keySet() read sequence?


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

Solution

  • 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());            
    }