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

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

profession has values:

  • engineer
  • Doctor<
7条回答
  •  孤城傲影
    2021-01-22 18:34

    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 {
        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{
    
        @Override
        public int compare(Person p1, Person p2) {
            return p1.getName().compareTo(p2.getName());
        }
    
    }
    
    public class PersonSortByAlphabeticalProfessionComparator implements Comparator{
    
        @Override
        public int compare(Person p1, Person p2) {
            return p1.getProfession().compareTo(p2.getProfession());
        }
    
    }
    

    Or this one you need:

    public class PersonSortByProfessionComparator implements Comparator {
    
        @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

提交回复
热议问题