How to sort a HashMap by value in Java?

To sort a HashMap by value in Java, first sort the entrySet() stream, then collect to LinkedHashMap.

Here's how you do it:

var hashMap = new java.util.HashMap<String, String>();
hashMap.put("1", "B");
hashMap.put("2", "C");
hashMap.put("3", "A");

var sortedMap = hashMap.entrySet().stream()
  .sorted(java.util.Map.Entry.comparingByValue())
  .collect(java.util.stream.Collectors.toMap(
    java.util.Map.Entry::getKey,
    java.util.Map.Entry::getValue,
    (e1, e2) -> e1, java.util.LinkedHashMap::new));

// {3=A, 1=B, 2=C}
System.out.println(sortedMap);