@dmitriyuvin
FullStack developer ( Laravel & Vue )

Как отсортировать HashMap по значению?

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

Дано предложение, я его разбиваю по пробелу, в один массив записываю слова, в других количество попаданий введнного символа в слове.
Получается два массива, я их соединяю в хеш-таблицу, получается (слово => кол-во введенного символа)
Как её осортировать по значению?
  • Вопрос задан
  • 4244 просмотра
Решения вопроса 2
sergey-gornostaev
@sergey-gornostaev Куратор тега Java
Седой и строгий
Вы можете добиться определённого порядка вывода элементов HashMap
words_counters.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    .forEach(System.out::println);

Но не отсортировать саму коллекцию, так как HashMap не гарантирует сохранения упорядоченности элементов.
1nawvi.gif
Если нужна упорядоченная реализация Map используйте TreeMap или LinkedHashMap.
Ответ написан
Комментировать
CellycoMobiles
@CellycoMobiles
indi developer @CellycoMobiles
Простите с телефона. Но думаю ответ в области Streams.
Например :
map.entryset().stream()
.sorted((entry1, entry2) -> customComparator.max(entry1.value, entry2.value))
.map(entry -> entry.getKey())
.collect(toList())
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Dmtm
Android
вместо HashMap использовать TreeMap с компаратором, сортировка будет происходить сразу при добавлении в мап
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽