Java Hashmap:交换两个值?
我可以交换 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果您只是在查找键已排序的 Map 之后,请使用
SortedMap
。您可以依赖键的自然排序(如其
Comparable
接口),也可以通过传递Comparator
来进行自定义排序。或者,您可以在
Entry
上调用setValue()
。就我个人而言,我只会使用
SortedMap
。Well, if you're just after a Map where the keys are ordered, use a
SortedMap
instead.You can rely on the natural ordering of the key (as in, its
Comparable
interface) or you can do custom ordering by passing aComparator
.Alternatively you can call
setValue()
on theEntry
.Personally I'd just go with a
SortedMap
.Map
或Entry
接口中没有类似的内容,但实现起来非常简单:There's nothing like that in the
Map
orEntry
interfaces but it's quite simple to implement: