简体   繁体   English

排除一个特定值时list.sort()如何工作?

[英]how list.sort() works when exclude one specific value?

I have a list 我有一个清单

List<String> names = new ArrayList<String>();
names.add("One");
names.add("Two");
names.add("Three");
names.add("Six");
names.add("Four");
names.add("Five");

I want this list to sort such that Six comes first, and then it should be in alphabetical order. 我希望该列表能够排序,使得“ Six”排在第一位,然后应该按字母顺序排列。

names.sort((x, y) -> {
            if (x.startsWith("S"))
                return -1;
            if (y.startsWith("S"))
                return 1; 
            return x.compareTo(y);
        });

This works fine. 这很好。 Why it is not working with only x.startswith("S") condition. 为什么它不能仅在x.startswith("S")条件下工作。 Why I need to add condition for y.startsWith("S") 为什么我需要为y.startsWith("S")添加条件

You don't know in which order the sort algorithm will compare your String s. 您不知道sort算法将比较String的顺序。 It might call compare("Two","Six") and it might call compare("Six","Two") . 它可能会调用compare("Two","Six") ,并且可能会调用compare("Six","Two") Therefore your Comparator must support both cases. 因此,您的Comparator必须支持这两种情况。

Besides, without checking startsWith("S") for both the first and second arguments, you are violating the Comparator contract, which requires that sgn(compare(x, y)) == -sgn(compare(y, x)) . 此外,如果不检查第一个和第二个参数的startsWith("S") ,就违反了Comparator合同,该合同要求sgn(compare(x, y)) == -sgn(compare(y, x))

BTW, it would be better to check equals("Six") instead of startsWith("S") . 顺便说一句,最好检查equals("Six")而不是startsWith("S") Otherwise your code will fail if your input will contain "Seven". 否则,如果您的输入包含“七”,则您的代码将失败。

collections.sort使用合并排序,合并排序的思想是通过阶段将列表划分为单个元素列表,并在这些阶段中按有序顺序将它们合并,因此不能保证您的“六个”将是第一个元素或第二个元素在比较中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM