Assume a map:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 1);
map.put("orange", 2);
Using Streams
LinkedHashMap<String, Integer> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue()) // ascending order
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new // preserve order
));
System.out.println(sortedMap);
Output:
{banana=1, orange=2, apple=3}
Summary:
.entrySet().stream()streams the map entries.Map.Entry.comparingByValue()sorts by value.Collectors.toMap(..., LinkedHashMap::new)preserves the sorted order.- Works for ascending; use
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))for descending order.
