Friday, May 22, 2020

Sort Characters by Frequency Using JAVA 8

class SortCharactersByFrequency {

    /**
     * Java Streams Approach
     * Time complexity : O(N)
     * Space complexity : O(N)
     */
    static String frequencySort(String s) {
        return s.chars()
                .mapToObj(Character::toString)                        //map to string character
                .collect(Collectors.groupingBy(Function.identity()))  //collect to Map<String, List<String>>
                .values()                                             //drop keys, we care only about values
                .stream()
                .sorted(Comparator.<List<String>>comparingInt(List::size).reversed()) //sort by list size in descending order
                .flatMap(strings -> strings.stream())                                 //flat map to stream of character strings
                .collect(Collectors.joining());                                       //build a string from the stream
    }
}

No comments:

Post a Comment