HashMaps don't support ordering the elements, so you have to start by copying your data into a data structure that permits sorting:
ArrayList<Map.Entry<List<String>, HashMap<List<String>, Long>> items =
new ArrayList<>(frequencyMap.entrySet());
Now, write a Comparator
that comparies Map.Entry
values:
class FrequencyComparator
implements Comparator<Map.Entry<List<String>, HashMap<List<String>, Long>> {
public int compare(Map.Entry<List<String>, HashMap<List<String>, Long>> a,
Map.Entry<List<String>, HashMap<List<String>, Long>> b) {
// code to get a's and b's frequency counts and compare them
}
}
Now, you can sort the array:
Collections.sort(items, new FrequencyComparator());
If it's expensive to get the frequency count for an item, then you could calculate it once for each item and then sort data structures containing these precalculated values:
class FrequencySortHelper implements Comparable<FrequencySortHelper> {
final List<String> key;
final int score;
public FrequencySortHelper(List<String> key, HashMap<List<String>, Long>> value) {
this.key = key;
score = getFrequencyCount(value);
}
public int compareTo(FrequencySortHelper other) {
int thisVal = this.score;
int anotherVal = other.score;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
}
ArrayList<FrequencySortHelper> items = new ArrayList<>(frequencyMap.size());
for (Map.Entry<List<String>, HashMap<List<String>, Long>> item : frequencyMap.entrySet()) {
items.add(new FrequencySortHelper(item.key(), item.value()));
}
Collections.sort(items); // Uses FrequencySortHelper's compareTo()
If you're thinking all this Map.Entry<List<String>, HashMap<List<String>, Long>>
stuff is awkward, you're right. You should think about defining some objects to contain this data, rather than just stringing together collections.