使用 Java 8 条流对 Map 的值(Set -> SortedSet)进行排序

Sort the values (Set -> SortedSet) of the Map with Java 8 Streams

如何对 Map<String, Set<String>> 的值进行排序,即使用流转换为 Map<String, SortedSet<String>>?

只需遍历每个条目并将 Set<T>(例如 HashSet<T>)转换为 SortedSet<T>(例如 TreeSet<T>),如:

Map<String, Set<String>> input = new HashMap<>();
Map<String, SortedSet<String>> output = new HashMap<>();
input.forEach((k, v) -> output.put(k, new TreeSet<>(v)));

或流为:

Map<String, Set<String>> input = new HashMap<>();
Map<String, SortedSet<String>> output = input.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, a -> new TreeSet<>(a.getValue())));