在某些情况下,特别是循环体内,HashMap或会出现失序问题。
因为HashMap 是无序的。具体地说,HashMap 不保证存储的键值对的顺序,也不保证迭代它的键值对的顺序。
这是因为 HashMap 使用哈希表来实现的,它通过哈希算法将键映射到存储桶中,而不是按照键的插入顺序或者键的自然顺序来存储。
可以考虑使用 LinkedHashMap 或 TreeMap。LinkedHashMap 保留了插入顺序,而 TreeMap 则根据键的自然顺序或者指定的比较器进行排序。
如:
/**
* 将指定字段重新插入到最后面
* @param maps
* @param distinctGGDM
* @return
*/
protected List<Map<String, Object>> sortToEndForMap(List<Map<String, Object>> maps, List<String> distinctGGDM) {
List<Map<String, Object>> updatedMaps = new ArrayList<>();
for (Map<String, Object> originalRow : maps) {
// 创建一个新的 Map 用于保存处理后的结果
Map<String, Object> updatedRow = new LinkedHashMap<>(originalRow);
// 移除并添加字段
for (String field : distinctGGDM) {
if (updatedRow.containsKey(field)) {
Object value = updatedRow.remove(field);
updatedRow.put(field, value);
}
}
//
updatedMaps.add(updatedRow);
}
return updatedMaps;
}
使用LinkedHashMap可以确保属性能严格按照插入顺序进行展示。
treeMap:
import java.util.Map;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
// 创建一个 TreeMap 对象
Map<Integer, String> treeMap = new TreeMap<>();
// 添加键值对
treeMap.put(3, "Apple");
treeMap.put(1, "Banana");
treeMap.put(2, "Orange");
// 遍历 TreeMap 并打印键值对
System.out.println("TreeMap 遍历结果:");
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
TreeMap 遍历结果:
Key: 1, Value: Banana
Key: 2, Value: Orange
Key: 3, Value: Apple