I was checking a post that wanted to know how to use Comparator
and a Orange fruit to be first all the time. From the post toString method was missing so I added to my code
@Override
public String toString(){
return fruitName +" " + fruitDesc;
}
The given answer to the post was
use 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());
}
});
output:
Orange Orange description
Apple Apple description
Banana Banana description
Pineapple Pineapple description
I was thinking why not Arrays.parallelSort
which I have been told good stuff about
using Arrays.parallelSort
code
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());
});
output:
Pineapple Pineapple description
Apple Apple description
Orange Orange description
Banana Banana description
To me sorting is sorting, why different answer form different method ?