Sorting map alphabetical


Removing brackets from list of anagrams

Hello, i have been asked to create new question insted of asking again in the same thread.

public static void main(String[] args) throws IOException {
    getAnagrams(new InputStreamReader(new URL("").openStream(),
            StandardCharsets.UTF_8)).forEach(items -> {
                for (String item : items) {
                    System.out.print(item + " ");
private static String canonicalize(String string) {

    return Stream.of(string.split("")).sorted().collect(Collectors.joining());

public static List<Set<String>> getAnagrams(Reader rr) {
Map<String, Set<String>> mapa = (Map<String, Set<String>>) new BufferedReader(rr).lines()
                                 .collect(Collectors.groupingBy(Main::canonicalize, Collectors.toSet()));
    return mapa.values().stream().filter(lista -> lista.size() > 4).collect(Collectors.toList());


How do i sort my output like “evil levi live veil vile”? Cuz for now i have “veil evil vile levi live”


What do you want to sort, the list of sets or the sets inside the list? If the sets then use a sorted set (e.g. TreeSet).
The other possibility is to sort the values and then collect them into a Set which retains insertion order, like LinkedHashSet. However the set will then not hold the data sorted if you later add elements. For this you will need sorted data-structures. Among the Sets the TreeSet would be a good candidate. Of course the sorting is not for free. Operations that need to search elements, like contains, add, remove etc. only run in O(log n) and not in O(1) (like in HashSet).



Here’s the easiest way I can think of

return mapa.values().stream()
    .filter(lista -> lista.size() > 4)
    .map(set -> new TreeSet<>(set))

TreeSet keeps its elements sorted.


Just as a note, you could replace the lambda in map by a method reference TreeSet::new.
You can use new as a method reference? Wow, I did not know that.
Yup, there are plenty of cool method references. You can even cast using references String.class::cast. Or String.class::isInstance for x instanceOf String and so on.



Add a Comment