1.字符串String是怎么排序的?
下面的代码,userName是String型的
userList.stream().sorted(Comparator.comparing(User::getUsername).reversed()).collect(Collectors.toList());
Comparator 类中的comparing方法,入参传入Function,用限界表达式限定传入的类型,通过Function的apply方法获取值。
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
这是String的比较方法,仔细分析,他是将两个字符串先转成char型,再逐一对比char,做减法,利用char型在java中是UTF-8编码,而UTF-8编码在0~128是和ASCII编码是一致的,A-Z 65-90 a-z 96-122 所以大写字母是在小写字母之前的
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}