java 如何使用键降序对哈希映射进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30842966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a hash map using key descending order
提问by Rahul
How to sort a hash map using key descending order. please explain with example. And how many way to sort a hash map. please explain in details
如何使用键降序对哈希映射进行排序。请举例说明。以及对哈希映射进行排序的方式有多少。请详细解释
回答by mastov
HashMap
s don't support sorting. They store entries in buckets, how they see it fit, just based on the hashCode
value of the keys. They are fine for storing things and looking them up afterwards, but unsuitable for iterating over their contents (which is what you apparently want to do) because you cannot rely on their order and iterating over it is usually expensive.
HashMap
s 不支持排序。他们将条目存储在桶中,他们认为它如何适合,仅基于hashCode
键的值。它们适用于存储东西并在之后查找它们,但不适合迭代它们的内容(这显然是您想要做的),因为您不能依赖它们的顺序并且迭代它通常很昂贵。
Try a TreeMap
instead. You can specify a custom comparator that does just the reverse of the default comparator. In that case your entries will be ordered in descendingorder. Collections.reverseOrder
will create such a comparator for you, you can use it like this:
换一个试试TreeMap
。您可以指定与默认比较器相反的自定义比较器。在这种情况下,您的条目将按降序排列。Collections.reverseOrder
将为您创建这样一个比较器,您可以像这样使用它:
new TreeMap<Integer, String>(Collections.reverseOrder());
回答by Ankur Singhal
Two ways to accomplish this:
有两种方法可以实现这一点:
Using HashMap
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 34); map.put("B", 25); map.put("C", 50); map.put("D", 50); // "duplicate" value System.out.println(entriesSortedByValues(map)); } static <K, V extends Comparable<? super V>> List<Entry<String, Integer>> entriesSortedByValues(Map<String, Integer> map) { List<Entry<String, Integer>> sortedEntries = new ArrayList<Entry<String, Integer>>(map.entrySet()); Collections.sort(sortedEntries, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) { return e2.getKey().compareTo(e1.getKey()); } }); return sortedEntries; }
Using Tree Map, writing own
Comparator
public class Test2 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 34); map.put("B", 25); map.put("C", 50); map.put("D", 50); MyComparator comp = new MyComparator(map); Map<String, Integer> newMap = new TreeMap(comp); newMap.putAll(map); System.out.println(newMap); } } class MyComparator implements Comparator { Map map; public MyComparator(Map map) { this.map = map; } @Override public int compare(Object o1, Object o2) { return (o2.toString()).compareTo(o1.toString()); } }
使用哈希映射
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 34); map.put("B", 25); map.put("C", 50); map.put("D", 50); // "duplicate" value System.out.println(entriesSortedByValues(map)); } static <K, V extends Comparable<? super V>> List<Entry<String, Integer>> entriesSortedByValues(Map<String, Integer> map) { List<Entry<String, Integer>> sortedEntries = new ArrayList<Entry<String, Integer>>(map.entrySet()); Collections.sort(sortedEntries, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) { return e2.getKey().compareTo(e1.getKey()); } }); return sortedEntries; }
使用Tree Map,编写自己的
Comparator
public class Test2 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 34); map.put("B", 25); map.put("C", 50); map.put("D", 50); MyComparator comp = new MyComparator(map); Map<String, Integer> newMap = new TreeMap(comp); newMap.putAll(map); System.out.println(newMap); } } class MyComparator implements Comparator { Map map; public MyComparator(Map map) { this.map = map; } @Override public int compare(Object o1, Object o2) { return (o2.toString()).compareTo(o1.toString()); } }
回答by Paarth Kotak
I suggest using this method as included in Java 8.
我建议使用 Java 8 中包含的这种方法。
List<Map.Entry<String, Integer>> sorted_map =
map_1.entrySet()
.stream()
.sorted(reverseOrder(Map.Entry.comparingByKey()))
.collect(Collectors.toList());
Here 'map_1' is the map you want to sort.
这里的“map_1”是您要排序的地图。
Now you can use the sorted_map variable to iterate and use for your purpose.
现在您可以使用 sorted_map 变量进行迭代并用于您的目的。
Make sure to :
确保 :
import static java.util.Collections.reverseOrder;
回答by faraz tanveer
Try this code
试试这个代码
public class MapUsingSort {
public static void main(String[] args) {
Map<Integer, String> abc = new HashMap<>();
abc.put(3, "a");
abc.put(6, "b");
abc.put(1, "c");
abc.put(4, "h");
abc.put(10, "k");
abc.put(9, "x");
// Map is stored in ArrayList
List<Entry<Integer,String>> sortedEntries = new
ArrayList<Entry<Integer,String>>(abc.entrySet());
Collections.sort(sortedEntries, new Comparator<Entry<Integer,String>>() {
@Override
public int compare(Entry<Integer, String> a, Entry<Integer, String> b)
{
//Sorting is done here make changes as per your need
// swap a and b for descending order in return statement
return a.getKey().compareTo(b.getKey());
}
});
for (Object object : sortedEntries) {
//print your data in your own way
System.out.println((Map.Entry)object);
}
}
}
回答by Alok Jain
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R");
System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}