Senior
Java Streams task: sort a Map<String, Integer> by value using streams.
sobes.tech AI
Answer from AI
To sort a Map<String, Integer> by value using Java Streams, you can do the following:
import java.util.*;
import java.util.stream.*;
public class SortMapByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 1);
map.put("orange", 2);
// Sort by value and collect into a LinkedHashMap to preserve order
Map<String, Integer> sorted = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println(sorted); // {banana=1, orange=2, apple=3}
}
}
Here, we create a stream from the entrySet, sort by value using Map.Entry.comparingByValue(), and then collect the result into a LinkedHashMap to preserve the order of elements.