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

This proposal, I break the space in one array write words, in other the number of hits vodnogo character in the word.
It turns out the two arrays, I put them in a hash table, it turns out (word => number entered character)
Her sortirovani by value?
April 7th 20 at 11:04
4 answers
April 7th 20 at 11:06
Solution
You can achieve a certain order of elements in HashMap
words_counters.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(the Comparator.reverseOrder()))
 .forEach(System.out::println);

But not to sort the actual collection, as HashMap does not guarantee the ordering of the elements.
1nawvi.gif
If you need a streamlined implementation of Map use TreeMap or LinkedHashMap.
April 7th 20 at 11:08
Solution
Excuse me from the phone. But I think the answer is in the area Streams.
For example :
map.entryset().stream()
.sorted((entry1, entry2) -> customComparator.max(entry1.value, entry2.value))
.map(entry -> entry.getKey())
.collect(toList())
do not understand - hassie commented on April 7th 20 at 11:11
April 7th 20 at 11:10
Solution
Try using comparator:
Test

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.*;
import java.lang.*;
import java.util.Scanner;

public class Main {

 public static boolean descending = false;
 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 is 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);
}

 Map<String, Integer> sortedMapDescending = sortByComparator(words_counters, descending);
printMap(sortedMapDescending);
}

 private static Map<String, Integer> sortByComparator(Map<String, Integer> toSortMap, final boolean order) {
 List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(toSortMap.entrySet());
 Collections.sort(list, new Comparator<Entry<String, Integer>>()
{
 public int compare(Entry<String, Integer> o1,
 Entry<String, Integer> o2)
{
 if (order) {
 return o1.getValue().compareTo(o2.getValue());
}
 else {
 return o2.getValue().compareTo(o1.getValue());
}
}
});

 Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
 for (Entry<String, Integer> entry : list) {
 sortedMap.put(entry.getKey(), entry.getValue());
}
 return sortedMap;
}

 public static void printMap(Map<String, Integer> map) {
 for (Entry<String, Integer> entry : map.entrySet()) {
 System.out.println("Key :" + entry.getKey() + " Value : "+ entry.getValue());
}
}
}
April 7th 20 at 11:12
use HashMap instead of TreeMap with a comparator, sorting will occur immediately when you add in the map

Find more questions by tags Java