1

Let's say I have an object like:

public class Fruit{

private String name;
private int quantity;

    Fruit(){}
    Fruit(String name, int quantity){
        this.name = name;
        this.quantity= quantity;
    }

    public int getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And I want to sort an array full of Fruit objects alphabetically by name. My initial thought, Arrays.sort(a.getName()); wouldn't work, because .getName() only works on individual objects. One idea I had was put all the names into an array, sort those alphabetically, then run a loop to sort the objects using this list, but that seems absurdly cumbersome.

Any ideas? As you can tell, I'm very new to working with objects in this manner.

  • suppose this [post](http://stackoverflow.com/questions/19471005/sorting-an-arraylist-of-objects-alphabetically) has the solution for your issue. suppose you need to implement `Comparator`. This may be a good place to [refer](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property). – Rajith Pemabandu Apr 21 '17 at 00:13

3 Answers3

3

Either you make your Fruit class Comparable by implementing the compareTo method, or you provide a custom Comparator to the Arrays.sort method:

Arrays.sort(fruits, Comparator.comparing(Fruit::getName));

This uses the Comparator.comparing method.

fps
  • 33,623
  • 8
  • 55
  • 110
1

I recommend you redefine your Fruit class to implement Comparable<Fruit> so that you can easily sort a Fruit[] by each elements' respective name field:

public class Fruit implements Comparable<Fruit> {
    // Code here...

    @Override
    public int compareTo(Fruit fruit) {
        return name.compareTo(fruit.name);
    }
}

Now, you can call Arrays#sort on Fruit[] and it will sort them lexicographically by name.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
1

You don't need to make your Fruit class implement Comparable<Fruit>; you can do it by passing a custom Comparator to the array, like this:

Array<Fruit> sortedArray = sort(fruitArray, new Comparator<Fruit>() {
   public int compare(Fruit left, Fruit right) {
       return left.name.compareTo(right.name);
   }
   public int equals(Object obj) { return 0; /* you can ignore this */ }
});
NRitH
  • 13,441
  • 4
  • 41
  • 44