Sobes.tech
Junior — Middle

What criterion is used to sort elements when calling the entrySet() method in a collection?

sobes.tech AI

Answer from AI

The entrySet() method returns a set of key-value pairs (Map.Entry) from a Map collection. By itself, entrySet() does not guarantee the order of elements.

The sorting criterion depends on the specific implementation of Map:

  • In HashMap, the order of elements is undefined (unsorted).
  • In LinkedHashMap, elements are ordered in insertion order.
  • In TreeMap, elements are sorted by key according to their natural ordering or a provided comparator.

Thus, if you call entrySet() on a TreeMap, the elements will be sorted by key. In other implementations, the order may be arbitrary or preserved by insertion.

Example:

Map<String, Integer> map = new TreeMap<>();
map.put("b", 2);
map.put("a", 1);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}
// Output:
// a=1
// b=2
What criterion is used to sort elements when calling… - sobes.tech