This is an alternative that does not require to create a custom Comparator
. I’m proposing it only for the sake of completeness.
- Split the String in words.
- Create a SortedMap.
- Iterate on the word list.
- 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).
- 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, String
s 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]