0

I have a question about the sequence of hash map. For example, in the following code:

public class MapEntrySetOrder {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        String[] l = new String[]{"Entry", "Set", "HashMap", "Order"};
        for (String s : l) {
            map.putIfAbsent(s, s);
        }
        for(Map.Entry<String, String> e : map.entrySet()) {
            System.out.println("key:" + e.getKey());
        }
    }
}

I know there is no order maintained in hashmap, but every time I print the keys thru a loop, there are all in same order, and the order is not from the beginning of the original list nor from the end of the original list:

key:Order
key:Entry
key:Set
key:HashMap

So how is the order decided. If it is in a random way, why every time I print they are the same result?

geocodezip
  • 158,664
  • 13
  • 220
  • 245
Hongli Bu
  • 461
  • 12
  • 37
  • If it were random, it would be called `RandomMap`. – terrorrussia-keeps-killing Jan 09 '21 at 00:02
  • 1
    All that matters is that the coder using the HashMap understands that they cannot rely on the order. Maybe you can find your answer in the HashMap source code? –  Jan 09 '21 at 00:03
  • 1
    Does this answer your question? [is the Java HashMap keySet() iteration order consistent?](https://stackoverflow.com/questions/1882762/is-the-java-hashmap-keyset-iteration-order-consistent) – Unmitigated Jan 09 '21 at 00:04
  • 2
    *why every time i print they are the same result?* try it on different java versions and you'll notice the difference. There is no guarantee of the order in a Hashmap – aran Jan 09 '21 at 00:07

2 Answers2

1

Use HashMap for fast non-ordered Map

Use LinkedHashMap for order of adding to the Map

Use TreeMap for any order you wish (with Comparator implementation)

Also I think you have same order each time because you use map.entrySet() instead of map.keySet()

MrFisherman
  • 720
  • 1
  • 7
  • 27
0

Hashmap does not guarantee any order. If you want ordered sequence use LinkedHashMap instead.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186