[Solved] to sort the word based on the number characters that contains in java [duplicate]


This is an alternative that does not require to create a custom Comparator. I’m proposing it only for the sake of completeness.

  1. Split the String in words.
  2. Create a SortedMap.
  3. Iterate on the word list.
  4. Populate it with “%03d%05d”.format(999-aWord.length(),i) -> aWord , where i is the index of aWord in in the word list. Here, the key is of the form xxxyyyyy, where xxx is an inverse of word length (998 for l=1, 997 for l=2, etc), so sorting if from longest to shortest, and yyyyy allows to differentiate words of the same length (as well as multiple occurrences of the same word).
  5. Result is theMap.values().
String input= "This is a string with differently sized words. This is another sentence." ;
String[] splitInput= input.split("[ .]") ;
TreeMap<String,String> theMap= new TreeMap<String,String>() ;
int index= 0 ;
for(String word: splitInput ) {
    if( word.length() > 0 ) {
        String key= String.format("%03d%05d",(999-word.length()),index) ;
        theMap.put(key,word);
        index++;
    }
}
System.out.println(theMap.values());

Produces output:

[differently, sentence, another, string, sized, words, This, with, This, is, is, a]

, which is correct. In fact, Strings of the same size are listed by position in input.

solved to sort the word based on the number characters that contains in java [duplicate]