我可以交换 Hashmap 的两个值的键,还是我需要做一些聪明的事情?
看起来像这样的东西:
Map.Entry<Integer, String> prev = null;
for (Map.Entry<Integer, String> entry: collection.entrySet()) {
if (prev != null) {
if (entry.isBefore(prev)) {
entry.swapWith(prev)
}
}
prev = entry;
}
最佳答案
好吧,如果您只是在排序键的 Map 之后,请使用 SortedMap
相反。
SortedMap<Integer, String> map = new TreeMap<Integer, String>();
您可以依靠键的自然排序(如在其 Comparable
接口(interface)中),或者您可以通过传递 Comparator
进行自定义排序。
或者,您可以在 Entry
上调用 setValue()
。
Map.Entry<Integer, String> prev = null;
for (Map.Entry<Integer, String> entry: collection.entrySet()) {
if (prev != null) {
if (entry.isBefore(prev)) {
String current = entry.getValue();
entry.setValue(prev.getValue();
prev.setValue(current);
}
}
prev = entry;
}
就我个人而言,我会选择 SortedMap
。
关于Java HashMap : Swap two values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1436290/