Reputation: 267
Hope you're doing well. I am having some trouble implementing the comparator method to sort a map by its values. I have written the comparator method, and am now trying to write a method that takes in an unsorted map as input, and uses the comparator implementation to return a sorted Map
. However, there is an error in one of the lines in my code which prevents it from compiling. The code for the sorting method I wrote is given below:
public static HashMap<String,ArrayList<String>>strongSorter(HashMap<String,ArrayList<String>> unsortedMap) {
MapComparator myCompare = new MapComparator(unsortedMap);
HashMap<String,ArrayList<String>> sortedMap = new HashMap<String,ArrayList<String>>(myCompare);
sortedMap.putAll(unsortedMap);
return sortedMap;
}
The error is present in the line where I try and create my sortedMap; Eclipse states that I am not allowed to pass in myCompare as an argument since my inputted arguments must match the inputs to a HashMap<String, ArrayList<String>>
. I don't know how to get around this and would really appreciate any help.
Thanks!
Upvotes: 1
Views: 878
Reputation: 47269
You can't have a sorted HashMap
. From the Javadoc (emphasis mine):
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
If you want ordering in your map, you should use a SortedMap
, such as TreeMap
. Also, note that TreepMap
sorts by the keys, so you may have to try another approach to this.
You could do this in Java 8 by using the comparingByValue()
method in Map.Entry
. Here is an example that returns a Stream
sorted by the maps values:
public static Stream<Map.Entry<String, List<String>>> strongSorter(Map<String, List<String>> unsortedMap) {
return unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(new MapComparator()));
}
Upvotes: 3
Reputation: 4252
You can use TreeMap as sorted map and specify your comparator.
Upvotes: 0