Saturday, June 25, 2016

User Defined Object Sorting

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

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...