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

前端 未结 7 1145
灰色年华
灰色年华 2021-01-22 18:02
class Person 
 {
 private String name;
 private String profession;
}

profession has values:

  • engineer
  • Doctor<
7条回答
  •  Happy的楠姐
    2021-01-22 18:29

    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.

提交回复
热议问题