Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting array of type object using Arrays.sort() method

I know how to sort an array of objects using Arrays.sort() method in following way.

Arrays.sort(array of primitive type);   
Arrays.sort(array of primitive type, from, to); 
Arrays.sort(array of an object type);   
Arrays.sort(array of an object type , from, to);    

but i have no idea about following two methods.

Arrays.sort(array of an object type , comparator);  
Arrays.sort(array of an object type , from, to, comparator);    

Can someone please let me know how to sort array of type object using these methods.I request you to add code or any link that directs to the .java class.I tried to search it but could not find it.

Thanks.

like image 338
nakul Avatar asked Jul 21 '26 07:07

nakul


2 Answers

Example:

class Person{  
   int id;  
   public getId(){return this.id;}  
//Other  stuff in your custom class
}  

Person[] persons = ...;//An array of person you get from somewhere
Arrays.sort(persons,new Comparator<Person>(){  
    @Override  
    public int compare(Person p1, Person p2){  
         return p1.getId() - p2.getId();  
   }  
} ); 
like image 72
Cratylus Avatar answered Jul 22 '26 19:07

Cratylus


Its easy:

Comparator Interface gives you control over the way you sort your Object.

An Object can be based on a key which is your wise.

For example, Account object should be sorted based on the AccountNumber

class Account {
    String AccountNumber; //Key 1 
    String AccountName;   //Key 2
    String GovtID;        //Key 3 
}

You can sort on either of three keys.

In order to have control on the sorting, you have to define a class that implements the Comparator interface, which will define the logic used for sorting.

class SortAccountByNumber implements Comparator<Account> {
    //Implement Unimplemented method 
    @Override
    public int compare(Account a1, Account a2) {
        //Read the specification for this method here in the Java Doc.
        return 0;
    }

}

Now to use this, simply call

  SortAccountByNumber varSortAccountByNumber = new SortAccountByNumber();
  Arrays.sort(arrayOfAccounts,varSortAccountByNumber);
like image 37
user1428716 Avatar answered Jul 22 '26 20:07

user1428716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!