Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java comparator, how to sort by integer?

Im trying to learn comparator in java and I have found this great example online, my question is how would this code be changed so that the pet names are ordered by age and in descending order so that the oldest is first and youngest is last?

class Dog implements Comparator<Dog>, Comparable<Dog>{ private String name; private int age; Dog(){ }  Dog(String n, int a){   name = n;   age = a; }  public String getDogName(){   return name; }  public int getDogAge(){   return age; }  // Overriding the compareTo method public int compareTo(Dog d){   return (this.name).compareTo(d.name); }  // Overriding the compare method to sort the age  public int compare(Dog d, Dog d1){   return d.age - d1.age; } }  public class Example{ public static void main(String args[]){   // Takes a list o Dog objects   List<Dog> list = new ArrayList<Dog>();    list.add(new Dog("Shaggy",3));   list.add(new Dog("Lacy",2));   list.add(new Dog("Roger",10));   list.add(new Dog("Tommy",4));   list.add(new Dog("Tammy",1));   Collections.sort(list);// Sorts the array list    for(Dog a: list)//printing the sorted list of names      System.out.print(a.getDogName() + ", ");    // Sorts the array list using comparator   Collections.sort(list, new Dog());   System.out.println(" ");   for(Dog a: list)//printing the sorted list of ages      System.out.print(a.getDogName() +"  : "+      a.getDogAge() + ", "); } } 
like image 377
Edmund Rojas Avatar asked May 22 '12 20:05

Edmund Rojas


People also ask

How do I sort using Comparator?

Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.

Which sorting algorithm is used by Comparator in Java?

The Comparator and Comparable interface don't do any sorting, so there is no sorting algorithm there. They just compare two Objects, something you need if you want to sort a list of those objects.


2 Answers

Simply changing

public int compare(Dog d, Dog d1) {   return d.age - d1.age; } 

to

public int compare(Dog d, Dog d1) {   return d1.age - d.age; } 

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {     private String name;     private int age;      public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {         // Overriding the compare method to sort the age         public int compare(Dog d, Dog d1) {             return d.age - d1.age;         }     };      Dog(String n, int a) {         name = n;         age = a;     }      public String getDogName() {         return name;     }      public int getDogAge() {         return age;     }      // Overriding the compareTo method     public int compareTo(Dog d) {         return (this.name).compareTo(d.name);     }  } 

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator Collections.sort(list, Dog.DESCENDING_COMPARATOR); 

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR =      Comparator.comparing(Dog::getDogAge).reversed(); 

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {     return DESCENDING_COMPARATOR.compare(d, d1); } 
like image 144
Jeshurun Avatar answered Sep 21 '22 17:09

Jeshurun


public class DogAgeComparator implements Comparator<Dog> {     public int compare(Dog o1, Dog o2) {         return Integer.compare(o1.getAge(), o2.getId());     } } 
like image 28
George Thekkan Avatar answered Sep 22 '22 17:09

George Thekkan