简体   繁体   中英

Sort java HashMap by values using O(n log n) complexity

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

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());
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM