Take into account all the substrings
TreeMap < String , Integer > a2 = new TreeMap < > ( ) ; for ( String s : a1 ) a2 . put ( s , a2 . getOrDefault ( s , 0 ) + 1 ) ; ArrayList < String > freshlist = new ArrayList < > ( ) ;