2

I have requirement that when sorted the list of objects, i wanted one object first in the order. Here is the list of object, when sorted using the some generic comparator, i want always orange fruit object first in the list, how can i do that using the comparator?

    Fruit pineappale = new Fruit("Pineapple", "Pineapple description"); 
    Fruit apple = new Fruit("Apple", "Apple description"); 
    Fruit orange = new Fruit("Orange", "Orange description"); 
    Fruit banana = new Fruit("Banana", "Banana description"); 


    List<Fruit> fruits = new ArrayList<Fruit>();

    fruits.add(pineappale);
    fruits.add(apple);
    fruits.add(orange);
    fruits.add(banana);

    Collections.sort(fruits, "some compator object"); 

    public class Fruit {

    private String fruitName;
    private String fruitDesc;


    public Fruit(String fruitName, String fruitDesc) {
        super();
        this.fruitName = fruitName;
        this.fruitDesc = fruitDesc;
    }

    public String getFruitName() {
        return fruitName;
    }
    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }
    public String getFruitDesc() {
        return fruitDesc;
    }
    public void setFruitDesc(String fruitDesc) {
        this.fruitDesc = fruitDesc;
    }   

}
user3157090
  • 517
  • 3
  • 12
  • 29

1 Answers1

3

Repleace Collections.sort(fruits, "some compator object");

with:

    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());
        }
    }); 
Jens
  • 67,715
  • 15
  • 98
  • 113
  • when I used Arrays.parallelSort I got different answer do you have any idea why? – Kick Buttowski Oct 06 '14 at 06:03
  • @KickButtowski No sorry . – Jens Oct 06 '14 at 06:14
  • http://stackoverflow.com/questions/26210842/different-output-from-arrays-parallelsort-and-collections-sort take a look at it if you like – Kick Buttowski Oct 06 '14 at 06:18
  • 1
    This is broken as it produces inconsistent results, e.g. if *both* names are `"orange"`. Further, these `null`-checks don’t make the slightest sense as in the last line the names are used without a `null`-check. – Holger Oct 06 '14 at 11:17
  • @h can you please be kind and post up your answer for this matter? please provide explanation asal – Kick Buttowski Dec 05 '14 at 07:43