Simple Java Solution using Lambdas


  • 0
    S
    class Solution {
    
        // Class used for sorting
        class Words{
            String wo;
            int freq;
            public Words(String w, int k){
                wo = w;
                freq = k;
            }
        }
    
        public List<String> topKFrequent(String[] w, int k) {
            HashMap<String, Integer> h = new HashMap<>();
            for(String s: w){
                if(!h.containsKey(s))
                    h.put(s, 1);
                else
                    h.put(s, h.get(s)+1);
            }
            // Making the list from Hashmap for applying Lambdas
            ArrayList<Words> a = new ArrayList<>();
            for(Map.Entry<String, Integer> e : h.entrySet())
                a.add(new Words(e.getKey(), e.getValue()));
            
           // Sorting alphabetically using Lambdas
            a.sort(Comparator.comparing(i->i.wo));
           // Reversing the alphabetical sort
            Collections.reverse(a);
           // Now sorting on the basis of frequency using Lambdas
            a.sort(Comparator.comparingInt(i->i.freq));
           // Now reversing the sort
            Collections.reverse(a);
    
            List<String> ans = new ArrayList<>();
            for(int i=0;i<k;i++)
                ans.add(a.get(i).wo);
            return ans;
        }
    }
    

Log in to reply
 

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