简体   繁体   中英

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

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

Just iterate over each entry and convert the Set<T> (eg HashSet<T> ) to a SortedSet<T> (eg TreeSet<T> ) as:

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

or with streams as:

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())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM