Java Hashmap:交换两个值? [英] Java Hashmap: Swap two values?
本文介绍了Java Hashmap:交换两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以交换两个Hashmap值的密钥,还是需要做一些巧妙的事情?
看起来像这样的东西:
Map.Entry< Integer,String> prev = null; (Map.Entry< Integer,String> entry:collection.entrySet()){
if(prev!= null){
if(entry.isBefore(prev)){
entry.swapWith(prev)
}
}
prev = entry;
}
解决方案
就在订购密钥的地图后面,使用 SortedMap
来代替。
SortedMap< Integer,String> map = new TreeMap< Integer,String>();
您可以依赖键的自然排序(如可比较的
接口),或者您可以通过传递比较器
来进行自定义排序。 $ b您可以在 Entry
上调用 setValue()
。
Map.Entry< Integer,String> prev = null; (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
。
Can I swap the keys of two values of a Hashmap, or do I need to do something clever?
Something that would look something like this:
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;
}
解决方案
Well, if you're just after a Map where the keys are ordered, use a SortedMap
instead.
SortedMap<Integer, String> map = new TreeMap<Integer, String>();
You can rely on the natural ordering of the key (as in, its Comparable
interface) or you can do custom ordering by passing a Comparator
.
Alternatively you can call setValue()
on the Entry
.
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;
}
Personally I'd just go with a SortedMap
.
这篇关于Java Hashmap:交换两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文