【问题标题】:Sort according to all fields in the list根据列表中的所有字段排序
【发布时间】:2020-06-30 21:47:38
【问题描述】:
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;
    }
}

我有一个有 5 个字段的 bean。我想按照 1 比 2 比 3 比 4 比 5 对所有五个字段进行排序

它由

字符串 细绳, 日期, 细绳 , 诠释。

如何根据 ID、姓名、加入日期、城市、年龄对列表中的 list<Emp> 进行排序

【问题讨论】:

  • Comparator.comparing(YourObject::getFirstString).thenComparing(YourObject::getSecondString)....
  • @Eugene 是否有任何集合 api 的内置方法,因为我正在使用 Comparator compareById = (Emp o1, Emp o2) -> o1.getId().compareTo( o2.getId ()); Collections.sort(Emp, compareById);
  • @Eugene 以上代码仅对 id 进行排序。
  • Collections.sort(employees, Comparator.comparing.....)

标签: java sorting java-8 comparator comparable


【解决方案1】:

您创建一个自定义Comparator

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

编辑:
为了解决 cmets 中的要求,您可以在排序之前根据城市字符串的长度对项目进行排序:

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));

【讨论】:

  • @dhS 需要详细说明吗?
  • 请检查更新后需要排序的 pojo .. 我有 List 我需要根据每个字段进行排序
  • 可能只是.thenComparing(Emp::getDate_of_join)
  • @Mureinik 谢谢让我知道一件事,如果我需要按特定顺序的城市,我能做些什么
  • @dhS 具体是什么命令?
猜你喜欢
  • 1970-01-01
  • 2018-03-07
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 2021-03-07
  • 2019-03-31
相关资源
最近更新 更多