Java Map sort key value pair on value with duplicate values

Description

Java Map sort key value pair on value with duplicate values

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main {

  public static <K,V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {

      @Override//w  ww  .ja  va 2s.co m
      public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
        return o2.getValue().compareTo(o1.getValue());
      }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) {
      Map.Entry<K, V> entry =  it.next();
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

  public static void main(String[] args) {

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    map.put("item1", 1);
    map.put("item2", 2);
    map.put("item3", 1);
    map.put("item4", 7);
    map.put("item5", 3);
    map.put("item6", 4);

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      System.out.println("Item is:" + entry.getKey() + " with value:"
          + entry.getValue());
    }

    Map<String, Integer> sortedMap = sortByValue(map);

    System.out.println();
    
    for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
      System.out.println("Item is:" + entry.getKey() + " with value:"
          + entry.getValue());
    }
  }
}



PreviousNext

Related