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.
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. Why I need to add condition for y.startsWith("S")
You don't know in which order the sort
algorithm will compare your String
s. It might call compare("Two","Six")
and it might call compare("Six","Two")
. Therefore your Comparator
must support both cases.
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))
.
BTW, it would be better to check equals("Six")
instead of startsWith("S")
. Otherwise your code will fail if your input will contain "Seven".
collections.sort使用合并排序,合并排序的思想是通过阶段将列表划分为单个元素列表,并在这些阶段中按有序顺序将它们合并,因此不能保证您的“六个”将是第一个元素或第二个元素在比较中
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.