-2

While iterating through the HashMap of Integer to String, suppose I insert values in the following order

HashMap<Integer, String> hash_map = new HashMap<>();
hash_map.put(0, "check");
hash_map.put(1, "ok");
hash_map.put(2, "what");
hash_map.put(4, "why");

When I iterate through the HashMap, using hash_map.entrySet(), will I iterate through it in order of insertion? Or will it be a random order?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Uddhav Bhagat
  • 63
  • 1
  • 2
  • 6
  • order in hashmap as well as hash set is not ogranized by order of insertion. – Ecto Aug 08 '20 at 20:01
  • 2
    From the [documentation of `HashSet`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/HashMap.html): "*This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.*" – Turing85 Aug 08 '20 at 20:01
  • I think this post could help you: https://stackoverflow.com/questions/1882762/is-the-java-hashmap-keyset-iteration-order-consistent – Lungu Daniel Aug 08 '20 at 20:01
  • You need `LinkedHashMap` to guarantee order. – Unmitigated Aug 08 '20 at 20:01
  • What is the difference between keySet and entrySet? – Uddhav Bhagat Aug 08 '20 at 20:05
  • @UddhavBhagat - `keySet` is the set of keys and `entrySet` is the set of entries (key=value pair). – Arvind Kumar Avinash Aug 08 '20 at 20:08
  • 1
    @UddhavBhagat What does the **documentation** say the difference is? --- [`keySet()`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/HashMap.html#keySet()) *"Returns a Set view of the **keys** contained in this map"* with return type `Set`. --- [`entrySet()`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/HashMap.html#entrySet()) *"Returns a Set view of the **mappings** contained in this map"* with return type `Set>`. – Andreas Aug 08 '20 at 20:16

1 Answers1

2

When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the right choice.

If you want the order of insertion try LinkedHashMap

try reading this : https://www.w3resource.com/java-tutorial/java-maps.php

Jayson Gonzaga
  • 140
  • 1
  • 4
  • 11