Asked  7 Months ago    Answers:  5   Viewed   27 times

I am trying figure out the order in which the values in a HashMap are/can be retrieved. Heres the code snippet for the same.

import java.util.HashMap;

public class HashMapExample {

   public static void main(String[] args) {
       HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
       hashmap.put(1, "apple" );
       hashmap.put(2, "lemon" );
       hashmap.put(3, "orange" );
       hashmap.put(4, "banana" );
       hashmap.put(5, "litchi" );
       hashmap.put(6, "mango" );
       hashmap.put(7, "papaya" );

       System.out.println(hashmap.size());

       for (String key : hashmap.values()) {
           System.out.println(key);
       }
   }
}

output:

7
apple
lemon
orange
banana
litchi
mango
papaya

The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in an arbitrary order. This is using Java 6.

 Answers

35

The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in random order.

The HashMap API does not define the order of iteration.

However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself.

In your case, you are using Integer keys which means that the hash values of the keys are the key values themselves. Also, you inserted the entries in key order. This leads (fortuitously!) to the iteration order matching the insertion order. But if you kept inserting more keys, you would find that the iteration order "wraps around". Then as the table goes through a series of resizes, the order will get progressively more and more scrambled.

In short, what you are seeing is an artefact of the hashtable implementation, and not something that you can (or should) sensibly make use of. Not least because it could change from one Java release to the next.

Tuesday, June 1, 2021
 
edorian
answered 7 Months ago
24

Use MySQL's FIELD() function:

SELECT name, description, ...
FROM ...
WHERE id IN([ids, any order])
ORDER BY FIELD(id, [ids in order])

FIELD() will return the index of the first parameter that is equal to the first parameter (other than the first parameter itself).

FIELD('a', 'a', 'b', 'c')

will return 1

FIELD('a', 'c', 'b', 'a')

will return 3

This will do exactly what you want if you paste the ids into the IN() clause and the FIELD() function in the same order.

Tuesday, June 1, 2021
 
EurekA
answered 7 Months ago
74

Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.

Thursday, August 12, 2021
 
Jason
answered 4 Months ago
41

Don't think there's much need for anything fancy here:

Map<String, Boolean> map = ...;
Map<String, Integer> newMap = Maps.newHashMapWithExpectedSize(map.size());
for (String key : map.keySet()) {
  newMap.put(key, 0);
}

If you do want something fancy with Guava, there is this option:

Map<String, Integer> newMap = Maps.newHashMap(
    Maps.transformValues(map, Functions.constant(0)));

// 1-liner with static imports!
Map<String, Integer> newMap = newHashMap(transformValues(map, constant(0)));
Friday, November 5, 2021
 
Sara
answered 4 Weeks ago
57

As of Java 8, an optimization was added to HashMap to deal with collisions when keys are Comparable:

To ameliorate impact, when keys are java.lang.Comparable, this class may use comparison order among keys to help break ties.

If your keys have a natural ordering that is inconsistent with equals(), any number of odd things may happen, and in this case it looks like the map is trying to keep track of keys using the natural ordering.

Tuesday, November 23, 2021
 
Chris Herrera
answered 1 Week ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share