D
D
Dmitriy2020-02-10 22:11:43
Java
Dmitriy, 2020-02-10 22:11:43

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);
        }
    }
}

Given a sentence, I split it by space, write words into one array, and the number of hits of the entered character in the other in the word.
It turns out two arrays, I combine them into a hash table, it turns out (word => number of entered character)
How to sort it by value?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-02-11
@dmitriyuvin

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);

But do not sort the collection itself, since HashMap does not guarantee that the order of the elements will be preserved.
1nawvi.gif
If you need an ordered Map implementation , use TreeMap or LinkedHashMap .

D
Dmtm, 2020-02-11
@Dmtm

instead of HashMap, use TreeMap with a comparator, sorting will occur immediately when added to the map

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question