class Person
{
private String name;
private String profession;
}
profession has values:
- engineer
- Doctor<
Two ways:
Comparable
interfaceComparator
With the first way you can sort the collection only by the one method compareTo
you will define
Your Person.java
class Person implements Comparable {
private String name;
private String profession;
@Override
public int compareTo(Person o) {
return this.profession.compareTo(o.getProfession());
}
public String getName() {
return name;
}
public String getProfession() {
return profession;
}
}
Then you need to call:
Collections.sort(yourCollection);
With the second way you can sort by one or more Comparator
, giving you the ability to compare the same collection with different criteria.
Example of two Comparator
public class PersonSortByNameComparator implements Comparator{
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
public class PersonSortByAlphabeticalProfessionComparator implements Comparator{
@Override
public int compare(Person p1, Person p2) {
return p1.getProfession().compareTo(p2.getProfession());
}
}
Or this one you need:
public class PersonSortByProfessionComparator implements Comparator {
@Override
public int compare(Person p1, Person p2) {
if(p1.getProfession().equalsIgnoreCase(p2.getProfession())
return 0;
if(p1.getProfession().equalsIgnoreCase("student")
return -1;
if(p1.getProfession().equalsIgnoreCase("engineer")
return 1;
if(p1.getProfession().equalsIgnoreCase("doctor")
return 1;
else
return -1;
}
}
And then call one of them:
Collections.sort(yourCollection, new PersonSortByNameComparator());
This blog article is really good written and you can some examples