226

I have a class named Fruit. I am creating a list of this class and adding each fruit in the list. I want to sort this list based on the order of fruit name.

public class Fruit{

    private String fruitName;
    private String fruitDesc;
    private int quantity;

    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;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

and I am creating its list using for loop

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

Fruit fruit;
for(int i=0;i<100;i++)
{
   fruit = new fruit();
   fruit.setname(...);
   fruits.add(fruit);
}

and I need to sort this arrayList using the fruit name of each object in the list

how??

ranjith
  • 4,526
  • 5
  • 27
  • 31

3 Answers3

427

Use a Comparator like this:

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

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

Idos
  • 15,053
  • 14
  • 60
  • 75
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 71
    Either this approach, using a `Comparator`, or @BMT's approach of making the objects implement `Comparable` would work. The difference is that by implementing `Comparable`, you're saying that the ordering is a fundamental part of the nature of the objects (like integers or strings), whereas by using a `Comparator`, you're saying that in this specific context, you want them ordered in a certain way. – Tom Anderson Aug 26 '13 at 10:32
  • 6
    what about the order of the sorting ?? ascending or descending ?? – Silent_Rebel Jun 01 '16 at 10:12
  • 3
    if the fruits names are case sensitive then you should use compareToIgnoreCase – user2977578 Aug 24 '16 at 00:10
  • I think the answer given under the section "since java-8" here is more succinct: http://stackoverflow.com/a/2784576/1372202 – Jannik Dec 13 '16 at 20:31
  • 1
    @Silent_Rebel It's ascending. You need to reverse the list after sorting it if you want it descending. It's tedious, agreed. – Alexis Dufrenoy Jan 30 '17 at 16:19
  • For those coming from Google, see here: https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html The documentation says, "Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second." Note that you can also use e.g. Integer.compare(int a, int b); – Andrew Apr 03 '17 at 15:37
  • Late in the game....But does not acsending or Descending depend on the positioning of the objcts in the compare function? Compare fruit1 with fruit2, would give a different result than comparing fruit2 with fruit1?? – PlickPlick May 01 '18 at 14:35
92

Implement Comparable interface to Fruit.

public class Fruit implements Comparable<Fruit> {

It implements the method

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

Collections.sort(fruitList);
Marco Johannesen
  • 13,084
  • 6
  • 31
  • 36
bNd
  • 7,512
  • 7
  • 39
  • 72
  • 8
    `Collections.sort(..)` also works for `ArrayList` where `T` is `Integer`, `Long`, `String`, which all have their `compareTo(..)` methods implemented. – Evgeni Sergeev May 04 '14 at 16:24
  • 13
    Comparable should be Comparable to work with compareTo(Fruit fruit) – Droid Chris Oct 20 '14 at 20:45
  • How would your approach look like if I wanted to add multiple different sort options, for example Override the compareTo method to order by the object name, but add another one for sorting by age, product id etc. etc. – b101 Dec 24 '16 at 19:21
  • 2
    @b101: In that case you would write multiple Comparators and just insert the right one at the right place. Something like: ``Comparator comp1 = new Comparator() { @\Override public int compare(Fruit fruit2, Fruit fruit1) { return fruit1.fruitName.compareTo(fruit2.fruitName); } }); Collection.sort(fruitList, comp1);`` – kaba713 Oct 10 '17 at 07:06
14

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77
newuser
  • 8,338
  • 2
  • 25
  • 33