Reputation: 6784
I know this question has been asked and answered many times. But almost all of the solutions have a computational complexity of O(n^2).
I am looking for a solution with O(n log n) complexity. Can someone please suggest?
Thanks heaps, Chaitanya
Upvotes: 1
Views: 5115
Reputation: 198023
Copy the entries to a List
, sort the List
by values; copy back into a LinkedHashMap
. I don't think a significantly better solution is even possible.
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<K, V>>() {
public int compare(Entry<K, V> left, Entry<K, V> right) {
return left.getValue().compareTo(right.getValue());
}
}
Map<K, V> sortedMap = new LinkedHashMap<K, V>(entries.size());
for (Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
Upvotes: 6