K most occurring strings | Java program for the above approach ; Function that returns list of K most frequent strings ; Hash map to store the frequency of each string ; Set the default frequency of each string 0 ; Lambda expression is used set the priority , if frequencies are not equal than the string with greater frequency is returned else the string which is lexically smaller is returned ; Traverse the HashMap ; Remove top ( N - K ) elements ; Order queue has K most frequent strings in a reverse order ; Reverse the ArrayList so as to get in the desired order ; Driver Code ; Given array ; Function Call ; Print the K most occurring strings
import java . util . * ; class FrequentWords { public static ArrayList < String > frequentWords ( ArrayList < String > arr , int K ) { HashMap < String , Integer > Freq = new HashMap < > ( ) ; for ( String word : arr ) { Freq . put ( word , Freq . getOrDefault ( word , 0 ) + 1 ) ; } PriorityQueue < String > Order = new PriorityQueue < > ( ( a , b ) -> ( Freq . get ( a ) != Freq . get ( b ) ) ? Freq . get ( a ) - Freq . get ( b ) : b . compareTo ( a ) ) ; for ( String word : Freq . keySet ( ) ) { Order . offer ( word ) ; if ( Order . size ( ) > K ) { Order . poll ( ) ; } } ArrayList < String > ans = new ArrayList < > ( ) ; while ( ! Order . isEmpty ( ) ) { ans . add ( Order . poll ( ) ) ; } Collections . reverse ( ans ) ; return ans ; } public static void main ( String [ ] args ) { int N = 3 , K = 2 ; ArrayList < String > arr = new ArrayList < String > ( ) ; arr . add ( " car " ) ; arr . add ( " bus " ) ; arr . add ( " car " ) ; ArrayList < String > ans = frequentWords ( arr , K ) ; for ( String word : ans ) { System . out . println ( word + " ▁ " ) ; } } }