我同意LinkedHashMap的东西。当我尝试按键对HashMap进行排序时,只是将我的发现和经验放在遇到问题时。
我创建HashMap的代码: 
HashMap<Integer, String> map;
@Before
public void initData() {
    map = new HashMap<>();
    map.put(55, "John");
    map.put(22, "Apple");
    map.put(66, "Earl");
    map.put(77, "Pearl");
    map.put(12, "George");
    map.put(6, "Rocky");
}
我有一个函数showMap,它打印地图条目: 
public void showMap (Map<Integer, String> map1) {
    for (Map.Entry<Integer,  String> entry: map1.entrySet()) {
        System.out.println("[Key: "+entry.getKey()+ " , "+"Value: "+entry.getValue() +"] ");
    }
}
现在,当我在排序之前打印地图时,它会按以下顺序打印: 
Map before sorting : 
[Key: 66 , Value: Earl] 
[Key: 22 , Value: Apple] 
[Key: 6 , Value: Rocky] 
[Key: 55 , Value: John] 
[Key: 12 , Value: George] 
[Key: 77 , Value: Pearl] 
这与放置地图键的顺序基本上不同。 
现在,当我使用地图键对其进行排序时: 
    List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
    Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
        @Override
        public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
    for (Map.Entry<Integer, String> entry : entries) {
        System.out.println("Putting key:"+entry.getKey());
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    System.out.println("Map after sorting:");
    showMap(sortedMap);
输出是: 
Sorting by keys : 
Putting key:6
Putting key:12
Putting key:22
Putting key:55
Putting key:66
Putting key:77
Map after sorting:
[Key: 66 , Value: Earl] 
[Key: 6 , Value: Rocky] 
[Key: 22 , Value: Apple] 
[Key: 55 , Value: John] 
[Key: 12 , Value: George] 
[Key: 77 , Value: Pearl] 
您可以看到按键顺序的差异。键的排序顺序很好,但复制映射的键的排序顺序仍与先前映射的顺序相同。我不知道这是否有效,但是对于具有相同键的两个哈希图,键的顺序相同。这暗示了这样的说法:键的顺序不能保证,但是对于具有相同键的两个映射,键的顺序可以相同,因为如果此JVM版本的HashMap实现是键插入算法的固有特性。
现在,当我使用LinkedHashMap将已排序的条目复制到HashMap时,我得到了预期的结果(这很自然,但这不是重点。重点在于HashMap的键顺序)
    HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
    for (Map.Entry<Integer, String> entry : entries) {
        System.out.println("Putting key:"+entry.getKey());
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    System.out.println("Map after sorting:");
    showMap(sortedMap);
输出: 
Sorting by keys : 
Putting key:6
Putting key:12
Putting key:22
Putting key:55
Putting key:66
Putting key:77
Map after sorting:
[Key: 6 , Value: Rocky] 
[Key: 12 , Value: George] 
[Key: 22 , Value: Apple] 
[Key: 55 , Value: John] 
[Key: 66 , Value: Earl] 
[Key: 77 , Value: Pearl]