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

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

profession has values:

  • engineer
  • Doctor<
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-22 18:41

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

提交回复
热议问题