Answer the question
In order to leave comments, you need to log in
How to sort HashMap by value?
import java.util.*;
public class Main {
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String RESET = "\u001B[0m";
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
StringBuffer sentence = new StringBuffer("Hello, my name is Dmitriy! I am 18 years old and it's the best text ever!");
String text = sentence.toString().toLowerCase();
System.out.print(GREEN + "Write ONLY one symbol ( letter ): " + RESET);
String symbol = in.nextLine();
int char_code = (int)symbol.charAt(0);
if(symbol.length() > 1) {
System.out.println(RED + "=== You entered more than one symbol! Try again! ===" + RESET);
} else if( (char_code < 64) || (90 < char_code && char_code < 97) || (char_code > 122)) {
System.out.println(RED + "=== You entered not a letter try again! ===" + RESET);
}
String[] words = text.split(" ");
int[] amount = new int[words.length];
for(int i = 0; i < words.length; i++) {
int counter = 0;
for(int j = 0; j < words[i].length(); j++) {
if(words[i].charAt(j) == char_code) {
counter++;
amount[i] = counter;
}
}
}
HashMap<String, Integer> words_counters = new HashMap<String, Integer>();
for (int l = 0; l < words.length; l++) {
words_counters.put(words[l], amount[l]);
}
for(String key: words_counters.keySet()) {
String word = key.toString();
String counts = words_counters.get(word).toString();
System.out.println(word + " => " + counts);
}
}
}
Answer the question
In order to leave comments, you need to log in
You can achieve a certain order of output of HashMap elements
words_counters.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEach(System.out::println);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question