Kic*_*ski 5 java sorting java-8
我正在检查一篇想知道如何使用的帖子,Comparator并且一直都是橙色水果.从帖子toString方法丢失所以我添加到我的代码
@Override
public String toString(){
return fruitName +" " + fruitDesc;
}
Run Code Online (Sandbox Code Playgroud)
帖子的答案是
使用Collection.sort
Collections.sort(fruits, new Comparator<Fruit>() {
@Override
public int compare(Fruit o1, Fruit o2) {
if (o1.getFruitName() != null && o1.getFruitName().equalsIgnoreCase("orange")){
return -1;
}
if (o2.getFruitName() != null && o2.getFruitName().equalsIgnoreCase("orange")){
return 1;
}
return o1.getFruitName().compareTo(o2.getFruitName());
}
});
Run Code Online (Sandbox Code Playgroud)
输出:
Orange Orange description
Apple Apple description
Banana Banana description
Pineapple Pineapple description
Run Code Online (Sandbox Code Playgroud)
我在想为什么不 Arrays.parallelSort被告知我的好东西
使用Arrays.parallelSort代码
Fruit[] arrayFruits = fruits.stream().toArray(Fruit[]::new);
Arrays.parallelSort(arrayFruits, (Fruit o1, Fruit o2) -> {
if (o1.getFruitName() != null && o1.getFruitName().equalsIgnoreCase("orange")){
return -1;
}
if (o2.getFruitName() != null && o2.getFruitName().equalsIgnoreCase("orange")){
return 1;
}
return o1.getFruitName().compareTo(o2.getFruitName());
});
Run Code Online (Sandbox Code Playgroud)
输出:
Pineapple Pineapple description
Apple Apple description
Orange Orange description
Banana Banana description
Run Code Online (Sandbox Code Playgroud)
对我来说排序是排序,为什么不同的答案形成不同的方法?
如果在TryJava8中运行该程序,我会得到正确排序的数组。我认为您可能打印了输入 ( fruits) 而不是输出 ( arrayFruits)。这就是说,您打开了一个有趣的话题,因为一般来说,您是对的,排序算法不能保证完整的顺序。一般来说,对于大型数组,如果两个元素等效但不相同(例如指向等效记录的不同指针),则算法不保证特定的顺序。一般来说,不同的算法会以不同的方式打破这种联系。
比较方法应满足顺序关系约束:
顺序关系应该是:
0我猜你最好返回)大多数排序算法隐式地假设此约束(它们不检查它们),因此提供O(n log n)时间复杂度。如果条件不成立,根据算法的实现,会得到不同的结果。
由于并行排序使用该MergeSort算法,而默认排序使用该QuickSort算法,因此这两种算法具有不同的行为。
相关主题:大多数排序算法都不稳定。假设两个项目“相等”,则不能保证如果A放置在原始数组中的A'之前,则 A将放置在结果数组中的A'之前。