简体   繁体   中英

Java Sorting User defined Objects

I want to sort Collection of Objects, which does not implement comparable or comparater interface. The problem is I cannot change the class design because I have only .class(no source code) file. How can I achive this?

You can sort by providing a custom Comparator . You don't need to implement Comparable .

See Collections.sort(List s, Comparator c) and the Collections ordering tutorial - specifically the section labelled Comparators :

What if you want to sort some objects in an order other than their natural ordering? Or what if you want to sort some objects that don't implement Comparable?

You can use comparator

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();
}
}

Lets say you need to sort Person objects list:

public class Person {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

It does not have to implement Comparable or Comparator interfaces. You can sort it like this:

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());
        }
    });
}

Take a look here .

- Your class doesn't need to implement Comparable , but instead, custom java.util.Comparator.

- Cause Comparator is like comparing the Object outside the Class whose objects are to be compared.

- You will need to use the Collections's method sort() .

Eg:

Collections.sort(List l , Comparator c)

- Comparator is also very useful when we want to sort an object on basis of More than on one of its attribute .

Lets say your class looks moreless like this:

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

Collection can be sort by using custom Comparator (Ex: If you have a class call Person and you want to sort according to the person's age)

public class CustomComparator implements Comparator<Person>{

    @Override
    public int compare(Person o1, Person o2) {
        if (o1.getAge() < o2.getAge()){
            return 1;
        }else{
            return 0;
        }
    }
}

Then you can just sort the list of Persons using this custom Comparator

Collections.sort(list, new CustomComparator());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM