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.
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();
}
} );
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With