首页 > 解决方案 > 使用 Java 8 Streams 对 Map 的值(Set -> SortedSet)进行排序

问题描述

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

标签: javajava-streamhashsetsortedset

解决方案


只需遍历每个条目并将 (eg ) 转换为Set<T>( HashSet<T>eg 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())));

推荐阅读