This question has already been answered:
- Sort map by java value 5 answers
let's say I have a map consisting of words and the number of repetitions in the text
TreeMap<String,Integer> treeMap = new TreeMap<>(); treeMap.put("CCC", 10); treeMap.put("KKK", 11); treeMap.put("AAA", 2); treeMap.put("BBB", 2); treeMap.put("DDD", 2); for(Map.Entry e : treeMap.entrySet()){ System.out.println(e.getKey()+" "+ e.getValue()); } output:
AAA 2 BBB 2 CCC 10 DDD 2 KKK 11 It is necessary that first sorted by the number of repetitions, if the words have the same number of repetitions, then sorted in lexicographical order.
must be like:
KKK 11 CCC 10 AAA 2 BBB 2 DDD 2