gogoWebsite

JAVA sorts Map by Value

Updated to 22 days ago
public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map){ class MapClass{ //Custom class saves key-value pairs private String key; private int value; public MapClass(String key, int value) { super(); this.key = key; this.value = value; } public String getKey() { return key; } public int getValue() { return value; } } class MapSortMethod implements Comparator<MapClass>{ //Implement the sorting method for custom classes @Override public int compare(MapClass o1, MapClass o2) { int result = Integer.compare(o1.getValue(), o2.getValue()); //Arrange ascending order by value size //int result = ((), ()); //Sorted in descending order by value size if(result != 0) return result; return o1.getKey().compareTo(o2.getKey()); //Arrange in key dictionary order when the values ​​are the same } } ArrayList<MapClass> mapclass = new ArrayList<MapClass>(); //Save custom class with ArrayList for(String k: map.keySet()) mapclass.add(new MapClass(k, map.get(k))); Collections.sort(mapclass, new MapSortMethod()); //Use the() method, the second parameter is a custom sorting method, and the Comparator interface needs to be implemented LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for(MapClass m: mapclass) sortedMap.put(m.getKey(), m.getValue()); return sortedMap; // Use LinkedHashMap to return the sorted Map }