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

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

profession has values:

  • engineer
  • Doctor<
相关标签:
7条回答
  • 2021-01-22 18:49

    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());  
    }  
    });
    
    0 讨论(0)
提交回复
热议问题