我会定义一个自定义Comparator
对象,然后用于Collections.sort
对列表进行排序。在这里,我定义了一个比较器,当用作排序参数时,它将所有元音移到末尾:
class VowelSort implements Comparator<Character>
{
private static boolean isVowel(Character c)
{
return "AEIOUaeiou".contains(c.toString());
}
public int compare(Character arg0, Character arg1)
{
final boolean vowel0 = isVowel(arg0), vowel1 = isVowel(arg1);
//if neither of the characters are vowels, they are "equal" to the sorting algorithm
if (!vowel0 && !vowel1)
{
return 0;
}
//if they are both vowels, compare lexigraphically
if (vowel0 && vowel1)
{
return arg0.compareTo(arg1);
}
//vowels are always "greater than" consonants
if (vowel0 && !vowel1)
{
return 1;
}
//and obviously consonants are always "less than" vowels
if (!vowel0 && vowel1)
{
return -1;
}
return 0; //this should never happen
}
}
在主要...
Collections.sort(chars,new VowelSort());
如果您也希望对辅音进行排序,只需更改
//if neither of the characters are vowels, they are "equal" to the sorting algorithm
if (!vowel0 && !vowel1)
{
return 0;
}
至
//compare consonants lexigraphically
if (!vowel0 && !vowel1)
{
return arg0.compareTo(arg1);
}