HashMap always returns values ordered by keys although documentation says it's not guaranteed:
public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(8, "B"); map.put(7, "C"); map.put(5, "A"); map.put(10, "Z"); map.put(3, "D"); map.put(1, "B"); System.out.println(map); printCollection(map); } private static void printCollection(Map<Integer, String> map) { for(Map.Entry<Integer, String> pair : map.entrySet()){ System.out.println(pair.getKey() + " " + pair.getValue()); } } Output: {1=B, 3=D, 5=A, 7=C, 8=B, 10=Z}
1 B 3 D 5 A 7 C 8 B 10 Z
new HashMap<>(4). That will give you a different order.