Sorting hashmap based on keys
Use sorted TreeMap
:
Map<String, Float> map = new TreeMap<>(yourMap);
It will automatically put entries sorted by keys. I think natural String
ordering will be fine in your case.
Note that HashMap
due to lookup optimizations does not preserve order.
How to sort HashMap keys
HashMaps do not store the sorted order of keys by definition. You can however accomplish this by acquiring an array of the keys via: Object[] keys = map.keySet().toArray();
Then sorting the list with Arrays: Arrays.sort(keys);
and finally iterating through each key and retrieving the value from the HashMap.
for(Object key : keys) {
System.out.println(map.get(key));
}
The sorting step here will make the algorithm run in O(n lg n) rather than O(n) which would be possible using a sorting data structure.
This will sort the list lexicographically. Since it looks like your question uses the common US date format, this will sort the list by day, then month and finally year. This is not likely correct. You can either use a year, month, day string format of the date, or adopt a more appropriate key object. Joda-Time's DateTime and DateTimeComparator would be quite useful. Simply use DateTime as the key and a DateTimeComparator instance when calling Arrays.sort(keys, comparator);
.
Sorting of Map based on keys
Are you specifically excluding TreeMap
for some external reason? If not you could obviously use TreeMap
with a specially made Comparator
.
Have you considered any of the other SortedMap
s?
If TreeMap
is definitely out I would extend HashMap
and make it look like there is always one more entry but that is certainly not a trivial piece of work. You should have a very good reason not to use a SortedMap
before going down this road.
Added
Here is an example of how you can make a particular entry always sort to the end using a TreeMap
:
// This key should always appear at the end of the list.
public static final String AtEnd = "Always at the end";
// A sample map.
SortedMap<String, String> myMap =
new TreeMap<>(
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.equals(AtEnd) ? 1 : o2.equals(AtEnd) ? -1 : o1.compareTo(o2);
}
});
private void test() {
myMap.put("Monday", "abc");
myMap.put("Tuesday", "def");
myMap.put("Wednesday", "ghi");
myMap.put(AtEnd, "XYZ");
System.out.println("myMap: "+myMap);
// {Monday=abc, Tuesday=def, Wednesday=ghi, Always at the end=XYZ}
}
I wonder if you are looking for some variant of that?
java: sort hashmap by keys and values
you can write your own comparator like below -
class MapValueKeyComparator<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparator<Map.Entry<K, V>> {
public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) {
int cmp1 = b.getValue().compareTo(a.getValue()); //can reverse a and b position for ascending/descending ordering
if (cmp1 != 0) {
return cmp1;
} else {
return a.getKey().compareTo(b.getKey()); //can reverse a and b position for ascending/descending ordering
}
}
}
Put all the map entries in the list and sort them -
HashMap<String, Integer> map = new HashMap<String, Integer> ();
map.put("Login to new", 27);
map.put("Failed login", 27);
map.put("Impossible", 21);
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new MapValueKeyComparator<String, Integer>());
for(Map.Entry<String, Integer> m : list){
System.out.println(m);
}
Output -
Failed login=27
Login to new=27
Impossible=21
Explanation - MapValueKeyComparator
sorts key and value of a given map, where values are sorted first and then the keys. In the main code putting all the map entries in the list so that it can be sorted using this comparator by using java's Collections
util class.
How to sort a hash map using key descending order
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());
Related Topics
Difference Between Validate(), Revalidate() and Invalidate() in Swing Gui
Field Required a Bean of Type That Could Not Be Found.' Error Spring Restful API Using Mongodb
How to Bring a Window to the Front
Constructor Overloading in Java - Best Practice
When to Use Wrapper Class and Primitive Type
Lambda Expression and Generic Defined Only in Method
Get Unicode Value of a Character
Using Java to Find Substring of a Bigger String Using Regular Expression
How to Read and Understand the Java Stack Trace
How to Use a Custom Font in Java
Setting Jpg Compression Level with Imageio in Java
How to Count Frequency of Characters in a String
Open Resource with Relative Path in Java
Class Has Been Compiled by a More Recent Version of the Java Environment
Data Access Object (Dao) in Java
Can Java Call Parent Overridden Method in Other Objects But Not Subtype