public class ExampleComparator {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("shyam",24));
list.add(new Person("jk",29));
list.add(new Person("paul",30));
list.add(new Person("ashique",4));
list.add(new Person("sreeraj",14));
for (Person person : list) {
System.out.println(person.getName()+ " "+ person.getAge());
}
Collections.sort(list,new PersonComparator());
System.out.println("After sorting");
for (Person person : list) {
System.out.println(person.getName()+ " "+ person.getAge());
}
}
}
public class Person {
private int age;
private String name;
Person (String name, int age){
setName(name);
setAge(age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person obj1, Person obj2) {
return obj1.getAge() - obj2.getAge();
}
}
class Test {
public int amount; //field u want to compare
// ...
}
Write your custom comparator for this class:
class TestAmountComparator implements Comparator<Test> {
@Override
public int compare(Test t1, Test t2) {
return Integer.valueOf(t1.amount).compareTo(Integer.valueOf(t2.amount))
}
}
To sort the list of your objects:
List<Test> list = new ArrayList<Test>(myTest); //your Test list
//sorting
Collections.sort(list, new TestAmountComparator()); //sort by amount
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public void someTest() {
LinkedList<Person> persons = new LinkedList<Person>();
persons.add(new Person());
//add as many as you want
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
});
}
No comments:
Post a Comment