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("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream(),
            StandardCharsets.UTF_8)).forEach(items -> {
                for (String item : items) {
                    System.out.print(item + " ");
                }
                System.out.println();
            });
}
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()
                                 .flatMap(Pattern.compile("\\W+")::splitAsStream)
                                 .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”

问题评论:

3  
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).

答案:

答案1:

Here’s the easiest way I can think of

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

TreeSet keeps its elements sorted.

答案评论:

    
Just as a note, you could replace the lambda in map by a method reference TreeSet::new.
1  
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.

原文地址:

https://stackoverflow.com/questions/47756207/sorting-map-alphabetical

Tags:

Add a Comment