这是一种不需要创建自定义Comparator 的替代方法。我只是为了完整性而提出它。
- 将字符串拆分为单词。
- 创建一个 SortedMap。
- 迭代单词列表。
- 用 "%03d%05d".format(999-aWord.length(),i) -> aWord 填充它,其中 i 是 aWord 在单词列表中的索引。这里,key 的形式是 xxxyyyyy,其中 xxx 是字长的倒数(998 表示 l=1,997 表示 l=2,等等),所以排序如果从最长到最短,并且 yyyyy 允许区分相同长度的单词(以及相同单词的多次出现)。
- 结果是 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());
产生输出:
[differently, sentence, another, string, sized, words, This, with, This, is, is, a]
,这是正确的。其实Strings大小相同,在input中是按位置列出的。