我对Java比较陌生,经常发现需要对值进行Map<Key,Value>排序。
由于这些值不是唯一的,我发现自己将keySet转换为一个数组,并使用自定义比较器通过数组排序对该数组进行排序,该比较器根据与该键关联的值进行排序。
有没有更简单的方法?
我对Java比较陌生,经常发现需要对值进行Map<Key,Value>排序。
由于这些值不是唯一的,我发现自己将keySet转换为一个数组,并使用自定义比较器通过数组排序对该数组进行排序,该比较器根据与该键关联的值进行排序。
有没有更简单的方法?
当前回答
我的解决方案是一种非常简单的方法,使用大多数给定的API。我们使用Map的特性通过entrySet()方法将其内容导出为Set。我们现在有一个包含Map.Entry对象的集合。
好的,集合不携带订单,但我们可以将内容放入ArrayList。它现在有一个随机顺序,但无论如何我们都会对它进行排序。
由于ArrayList是一个集合,所以我们现在使用Collections.sort()方法来将秩序带入混乱。因为我们的Map.Entry对象没有实现我们需要的那种比较,所以我们提供了一个自定义比较器。
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("Z", "E");
map.put("G", "A");
map.put("D", "C");
map.put("E", null);
map.put("O", "C");
map.put("L", "D");
map.put("Q", "B");
map.put("A", "F");
map.put(null, "X");
MapEntryComparator mapEntryComparator = new MapEntryComparator();
List<Entry<String,String>> entryList = new ArrayList<>(map.entrySet());
Collections.sort(entryList, mapEntryComparator);
for (Entry<String, String> entry : entryList) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
其他回答
这是Anthony答案的变体,如果存在重复值,则该答案无效:
public static <K, V extends Comparable<V>> Map<K, V> sortMapByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
final V v1 = map.get(k1);
final V v2 = map.get(k2);
/* Not sure how to handle nulls ... */
if (v1 == null) {
return (v2 == null) ? 0 : 1;
}
int compare = v2.compareTo(v1);
if (compare != 0)
{
return compare;
}
else
{
Integer h1 = k1.hashCode();
Integer h2 = k2.hashCode();
return h2.compareTo(h1);
}
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
注意,如何处理空值还很难说。
这种方法的一个重要优点是它实际上返回了一个Map,这与这里提供的其他解决方案不同。
从…起http://www.programmersheaven.com/download/49349/download.aspx
private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
List<Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
}
});
Map<K, V> result = new LinkedHashMap<>();
for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {
Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
如果没有大于地图大小的值,可以使用数组,这应该是最快的方法:
public List<String> getList(Map<String, Integer> myMap) {
String[] copyArray = new String[myMap.size()];
for (Entry<String, Integer> entry : myMap.entrySet()) {
copyArray[entry.getValue()] = entry.getKey();
}
return Arrays.asList(copyArray);
}
如果您的Map值实现Comparable(例如String),那么这应该会起作用
Map<Object, String> map = new HashMap<Object, String>();
// Populate the Map
List<String> mapValues = new ArrayList<String>(map.values());
Collections.sort(mapValues);
如果映射值本身没有实现Comparable,但您有一个Comparable实例可以对它们进行排序,请将最后一行替换为:
Collections.sort(mapValues, comparable);
为每个值创建一个条目列表,其中对值进行排序需要Java 8或更高版本
Map<Double,List<Entry<String,Double>>> sorted =
map.entrySet().stream().collect( Collectors.groupingBy( Entry::getValue, TreeMap::new,
Collectors.mapping( Function.identity(), Collectors.toList() ) ) );
使用映射{[A=99.5],[B=67.4],[C=67.3],[D=67.3]}得到{67.3=[D=67.3],67.4=[B=67.4,C=67.4],99.5=[A=99.5]}
…以及如何逐个访问每个条目:
sorted.entrySet().forEach( e -> e.getValue().forEach( l -> System.out.println( l ) ) );
D=67.3 B=67.4 C=67.4 A=99.5