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