Java to sort list of custom object on the basis of string

北城余情 提交于 2020-12-26 09:39:13

问题


class Person 
 {
 private String name;
 private String profession;
}

profession has values:

  • engineer
  • Doctor
  • Teacher
  • student

I have list of person and want to sort it on the basis of Profession. engineer comes first then Doctor and then Teacher and then student.

Is it possible to sort it with comparable interface.


回答1:


You can sort your custom object using Collection.sort method like this,

Collections.sort(list, new Comparator(){

        public int compare(Object o1, Object o2) {
            Person p1 = (Person) o1;
            Person p2 = (Person) o2;
            return p1.getProfession().compareToIgnoreCase(p2.getProfession());
        }

    });

To Sort in reverse order just make your return statement line like this,

p2.getProfession().compareToIgnoreCase(p1.getProfession());

This will directly make your list sorted.




回答2:


Add enum to your variables:

class Person {
   private String name;
   private String profession;
   private enum enumProffesion
    {
        Doctor, Teacher, student;
    }
}

After that could add function to the Person class which would give you value of the profession:

public int professionValue()
{
    enumProffesion enumValue= enumProffesion.valueOf(proffesion);
    switch (enumValue) {
    case Doctor: return 1; break;
    case Teacher: return 2; break;
    case student: return 3; break;
    default: return null;
    }
}

After that you just implement logic that will sort all Persons. For that you can help your self with this answer: sorting integers in order lowest to highest java




回答3:


Implement Comparable

Yes you can implement Comparable. Create a method compareTo(Person obj) and then write your custom logic. You can compare alphabetically or whatever other algorithm you want - for example engineer before doctor because he makes more money :) For alphabetic comparing you can do it like that:

class Person implements Comparable<Person> {

@Override
public int compareTo(Person o) {
    return this.profession.compareTo(o.getProfession());

  }
  private String name;
  private String profession;
}

After that you just use the Collections.sort




回答4:


Enum

You can do it easily if replace profession field by enum:

class Person implements Comparable<Person> {
    private String name;
    private Profession profession;

    // by this we'll define natural ordering based on ordering
    // in which `Profession` enum values are declared
    @Override
    public int compareTo(Person p) {
        return this.profession.compareTo(p.profession);
    } 
}

And here's Profession enum:

public enum Profession {
    ENGINEER("engineer"), DOCTOR("Doctor"), TEACHER("Teacher"), STUDENT("student");
    
    private String displayName;
    
    Profession(String dn) {
        this.displayName = dn;
    }

    @Override
    public String toString() {
        return this.displayName;
    }
}

If you are new to the enum facility in Java, see Oracle tutorial.




回答5:


Add getter and setter for profession in Person class and simply use below code

class Person {
   private String name;
   private String profession;
   public String getProfession() {  
        return profession;  
    }  
    public void setProfession(String profession) {  
        this.profession = profession;  
    }
}


List<Person> personList = new ArrayList<Person>(); 

Person p1 = new Person();
p1.setProfession("Engineer"); 
personList.add(p1);

Person p2 = new Person();
p2.setProfession("Doctor"); 
personList.add(p2);

Person p3 = new Person();
p3.setProfession("Teacher"); 
personList.add(p3);

Person p4 = new Person();
p4.setProfession("student"); 
personList.add(p4);


Collections.sort(personList, new Comparator() {  
@Override  
public int compare(Object obj1, Object obj2) {  
Person p1 = (Person)obj1;  
Person p2 = (Person)obj2;  
return p1.getProfession().compareToIgnoreCase(p2.getProfession());  
}  
});



回答6:


Two ways:

  1. Implement the Comparable interface
  2. Create a Comparator

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<Person> {
    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<Person>{

    @Override
    public int compare(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
    }

}

public class PersonSortByAlphabeticalProfessionComparator implements Comparator<Person>{

    @Override
    public int compare(Person p1, Person p2) {
        return p1.getProfession().compareTo(p2.getProfession());
    }

}

Or this one you need:

public class PersonSortByProfessionComparator implements Comparator<Person> {

    @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




回答7:


My suggestion -

1. Create a new class Profession -

class Profession{

   public Profession(Integer id, String prefessionName){
      this.id=id;
      this.prefessionName=prefessionName;
   }
   Integer id;
   String professionName;

}  

2. Now give Id to each Profession object/instance maintaining the order. For example -

   Profession engineer = new Profession(1, "Engineer"); //since Engineer is in first place 
   Profession doctor = new Profession(2, "Doctor"); //since Doctor is in second place
   Profession teacher = new Profession(3, "Teacher");
   Profession student = new Profession(4, "Student");

3. Now sort the Profession for id using compareable interface.



来源:https://stackoverflow.com/questions/30100836/java-to-sort-list-of-custom-object-on-the-basis-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!