Java streams are cool :)


  • 0
    public String frequencySort(String s) {
            HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
            s.chars().forEach(c->hm.put((char)c, hm.getOrDefault((char)c,0)+1));
            StringBuilder sb = new StringBuilder();
            hm.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEach(e->repeat(e,sb));
            return sb.toString();
    }
    
    public static void repeat(Map.Entry e, StringBuilder sb){
           char [] chars = new char[(int)e.getValue()];
           Arrays.fill(chars, (char)e.getKey());
           sb.append(chars);
    }
    

  • 0
    R

    Here is my stream version

    public String frequencySort(String s){
            return  s.chars()
                    .boxed()
                    .collect(
                            Collectors.groupingBy(
                                    Function.identity(),
                                    Collectors.counting()
                            ))
                    .entrySet()
                    .stream()
                    .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
                    .collect(Collectors.toMap(
                            Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new
                    ))
                    .entrySet()
                    .stream()
                    .map(
                            a -> Collections.nCopies(
                                            a.getValue().intValue()
                                           ,new StringBuilder().append((char) a.getKey().intValue())
                                    )
                                    .stream()
                                    .reduce(new StringBuilder(), (x, y) -> x.append(y))
                    )
                    .reduce(new StringBuilder(), (a, b) -> a.append(b)).toString();
        }
    

  • 0
    W

    You can use compute method to make it more consice.

    public String frequencySort(String s) {
        StringBuilder sb = new StringBuilder();
        Map<Integer, Integer> map = new HashMap<>();
        s.chars().forEach(c -> map.compute(c, (k, v) -> Objects.isNull(v) ? 1 : v + 1));
        map.entrySet().stream().sorted(Entry.comparingByValue(Comparator.reverseOrder())).forEach(e -> push(e, sb));
        return sb.toString();
    }
    
    private void push(Entry<Integer, Integer> e, StringBuilder sb) {
        for (int c = e.getKey(), times = e.getValue(); times-- > 0; sb.append((char) c));
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.