如何排序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())));