I was checking a post that would like to know how to use Comparator and Orange Fruit to be the first all the time. There was no post toString method, so I added to my code
@Override public String toString(){ return fruitName +" " + fruitDesc; }
This response to the message 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 thought, why not the Arrays.parallelSort , which I was told good things about
read more here
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
Link to the message here
Sorting sorts for me, why are different forms of response different?
source share