There is a code:

import java.security.KeyStore; import java.util.*; import java.util.stream.Collectors; public class C { HashMap<String, Integer> map = new HashMap<String, Integer>(); ValueComparator bvc = new ValueComparator(map); TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(bvc); public static void main(String[] args) { FruitSort fruitSort = new C().new FruitSort(); fruitSort.enterChat(); } class FruitSort { private String[] massivFruit; void enterChat() { Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); massivFruit = new String[number]; for (int i = 0; i < massivFruit.length; i++) { Scanner scannerName = new Scanner(System.in); String name = scannerName.next(); massivFruit[i] = name; } sortFruit(); } void sortFruit() { for (int i = 0; i < massivFruit.length; i++) { int count = 0; for (int j = 0; j < massivFruit.length; j++) { if (massivFruit[i].equals(massivFruit[j])) { count++; } } map.put(massivFruit[i], count); } sorted_map.putAll(map); System.out.println(sorted_map); for (String key : sorted_map.keySet()) { System.out.println(key); } } } class ValueComparator implements Comparator<String> { Map<String, Integer> base; public ValueComparator(Map<String, Integer> base) { this.base = base; } public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } } } } 

It seems that everything works but one thing. If I do testing for example, I enter:

 6 Π―Π±Π»ΠΎΠΊΠΎ Π›ΠΈΠΌΠΎΠ½ Дыня Дыня Π›ΠΈΠΌΠΎΠ½ Π―Π±Π»ΠΎΠΊΠΎ 

That is the conclusion:

 {Π›ΠΈΠΌΠΎΠ½=2, Π―Π±Π»ΠΎΠΊΠΎ=2, Дыня=2} Π›ΠΈΠΌΠΎΠ½ Π―Π±Π»ΠΎΠΊΠΎ Дыня 

My question is the following. I need the following order:

Π―Π±Π»ΠΎΠΊΠΎ = 2 , Π›ΠΈΠΌΠΎΠ½ = 2, Дыня = 2

And for some reason elements are interchanged. It is possible to make their order be such that if the values ​​of the values match, then the order remains the same as it was entered. If for example the values larger than the others, then it is printed at the top. For example:

 5 Π›ΠΈΠΌΠΎΠ½ Π―Π±Π»ΠΎΠΊΠΎ Π―Π±Π»ΠΎΠΊΠΎ Π‘Π°Π½Π°Π½ Киви 

Should output:

 Π―Π±Π»ΠΎΠΊΠΎ = 2, Π‘Π°Π½Π°Π½ = 1,Киви = 1,Π›ΠΈΠΌΠΎΠ½ = 1 
  • In this case, you need a comparator, which as a secondary key takes into account the sequence number of the item under which it first appeared. - MBo
  • This map that you wanted from him - Sanaev
  • one
    Possible duplicate question: Sort the Map by the lowest value - Sergey Gornostaev

0