按值对LinkedHashMap进行排序 [英] Sorting LinkedHashMap by value
问题描述
如何使用值对LinkedHashMap进行排序?
How can you sort a LinkedHashMap using the value ?
是否可以将条目插入LinkedHashMap中,以便根据其值顺序插入?
Is there a way to insert entries into a LinkedHashMap so that they are inserted in order based on their value ?
推荐答案
如何使用该值对LinkedHashMap进行排序?
How can you sort a LinkedHashMap using the value?
LinkedHashMap
未进行排序,而是按插入顺序进行排序.
LinkedHashMap
is not sorted, it is ordered by order of insertion.
如果您的目标是重新排序地图,则可以执行类似的操作
If your goal is to reorder the Map, you might do something like
static <K, V> void orderByValue(
LinkedHashMap<K, V> m, final Comparator<? super V> c) {
List<Map.Entry<K, V>> entries = new ArrayList<>(m.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> lhs, Map.Entry<K, V> rhs) {
return c.compare(lhs.getValue(), rhs.getValue());
}
});
m.clear();
for(Map.Entry<K, V> e : entries) {
m.put(e.getKey(), e.getValue());
}
}
我们将所有条目放入一个列表中,对列表进行排序,然后以新的顺序将这些条目放回到地图中.
We put all the entries in a List, sort the List, then put the entries back in the Map in the new order.
这是针对那些偏爱者的Java 8翻译:
Here's a Java 8 translation for those inclined:
static <K, V> void orderByValue(
LinkedHashMap<K, V> m, Comparator<? super V> c) {
List<Map.Entry<K, V>> entries = new ArrayList<>(m.entrySet());
m.clear();
entries.stream()
.sorted(Comparator.comparing(Map.Entry::getValue, c))
.forEachOrdered(e -> m.put(e.getKey(), e.getValue()));
}
(出于好奇,可以将其浓缩,尽管效率较低):
(Which, out of curiosity, can be condensed to, although it is less efficient):
static <K, V> void orderByValue(
LinkedHashMap<K, V> m, Comparator<? super V> c) {
new ArrayList<>(m.keySet()).stream()
.sorted(Comparator.comparing(m::get, c))
.forEachOrdered(k -> m.put(k, m.remove(k)));
}
有没有一种方法可以将条目插入LinkedHashMap中,以便根据其值顺序插入它们?
Is there a way to insert entries into a LinkedHashMap so that they are inserted in order based on their value?
不.看上面. LinkedHashMap
未排序.
如果您的目标是对地图进行分类,则需要使用 TreeMap
;但是这样做有问题.地图中的条目必须具有唯一值.请参见此处和
If your goal is to keep the Map sorted, you need to use a TreeMap
; however there are problems with doing so. Entries in the Map need to have unique values. See here and here.
这篇关于按值对LinkedHashMap进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!