Search code examples
javajava-streamhashsetsortedset

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


How to sort values of the Map<String, Set<String>> i.e. convert to Map<String, SortedSet<String>> with streams?


Solution

  • Just iterate over each entry and convert the Set<T> (e.g. HashSet<T>) to a SortedSet<T> (e.g. 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())));