如何使用我自己的键在HashMap中安排现有的键?

时间:2016-07-15 02:51:12

标签: java android arraylist hashmap

我有一个HashMap,其中键代表ClassModel的顺序。众所周知,HashMaps在检索或输出密钥时不会保持密钥的顺序。我还有一个ArrayList,它存储了ClassModels的预期排列顺序。例如,当我从Hashmap中检索键值时,我会得到类似Car 1,Car 4,Car 3,Car 5和Car 2的内容.AllList值具有预期的排列值顺序;汽车1,汽车2,汽车3,汽车4和汽车5.我想根据ArrayList中的键来订购它们。我的代码如下:

    for (HashMap.Entry<String, FloorPlanModel> existingKeys : floorPlanKeys.entrySet()) {
        Log.d(LOG_TAG, "existingKeys entries = " + existingKeys.getKey());
    }
    for (String newKeys : buildingModel.getFpKeys()) {
        Log.d(LOG_TAG, "newKeys entries = " + newKeys);
    }

输出的时刻是:

existingKeys entries = floorplan0
existingKeys entries = floorplan2
existingKeys entries = floorplan3
existingKeys entries = floorplan4
existingKeys entries = floorplan1

newKeys entries = floorplan0
newKeys entries = floorplan1
newKeys entries = floorplan2
newKeys entries = floorplan3
newKeys entries = floorplan4

我应该将第二个for循环置于第一个for循环中,但是如何迭代HashMap中的每个值并使用ArrayList中的值对它们进行排序?如果我覆盖它们,那么hashmap中的值会改变吗?

我忘了提到我无法使用TreeMaps。我需要手动安排它们。

1 个答案:

答案 0 :(得分:2)

TreeMap是你的朋友。使用已排序/可排序键映射。