Search code examples
javasortingjava-8comparatorcomparable

Sort according to all fields in the list


import java.util.Date;

public class Emp {
    public Emp() {
    }

    private int Id;
    private String name;
    private Date date_of_join;
    private String city;
    private int age;
    public int getId() {
        return Id;
    }
    public void setId(int id) {
        Id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getDate_of_join() {
        return date_of_join;
    }
    public void setDate_of_join(Date date_of_join) {
        this.date_of_join = date_of_join;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

I have a bean with 5 fields. I want to sort all the five field according to 1 than 2 than 3rd than 4 and than 5

It consists of

String String, Date, String , Int.

What could i do to sort the list<Emp> inside the list according to id, name, date of join, city, age


Solution

  • You create a custom Comparator:

    myList.sort(Comparator.comparingInt(Emp::getId)
                          .thenComparing(Emp::getName)
                          .thenComparing(Emp::getDate_of_join)
                          .thenComparing(Emp::getCity)
                          .thenComparingInt(Emp::getAge));
    

    EDIT:
    To address the requirement in the comments, you could sort the items accoring to the length of the city's string before sorting by it:

    myList.sort(Comparator.comparingInt(Emp::getId)
                          .thenComparing(Emp::getName)
                          .thenComparing(Emp::getDate_of_join)
                          .thenComparingInt(e -> e.getCity().length())
                          .thenComparing(Emp::getCity)
                          .thenComparingInt(Emp::getAge));