Comprator sorts one object always on top

I have a requirement that when sorting a list of objects, I want one object first in order. Here is the list of objects, when sorting using some kind of general comparator, I want the orange fruit object to always be the first in the list, how can I do this 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; } } 
+2
source share
1 answer

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

from:

  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()); } }); 
+2
source

Source: https://habr.com/ru/post/1204080/


All Articles