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
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.
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 descending order. Collections.reverseOrder
will create such a comparator for you, you can use it like this:
new TreeMap<Integer, String>(Collections.reverseOrder());
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()); } }
I suggest using this method as included in 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.
Now you can use the sorted_map variable to iterate and use for your purpose.
Make sure to :
import static java.util.Collections.reverseOrder;
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);
}
}
}
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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.