根据列表中的所有字段排序
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;
}
}
我有一个包含 5 个字段的 bean。我想根据 1 比 2 比 3 比 4 比 5
对所有五个字段进行排序
它包括
字符串
细绳,
日期,
细绳 ,
国际
我该怎么做才能根据 ID、姓名、加入日期、城市、年龄对列表中的 list<Emp>
进行排序
您创建了一个自定义 Comparator
:
myList.sort(Comparator.comparingInt(Emp::getId)
.thenComparing(Emp::getName)
.thenComparing(Emp::getDate_of_join)
.thenComparing(Emp::getCity)
.thenComparingInt(Emp::getAge));
编辑:
为了解决评论中的要求,您可以在排序之前根据城市字符串的长度对项目进行排序:
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));
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
:
myList.sort(Comparator.comparingInt(Emp::getId)
.thenComparing(Emp::getName)
.thenComparing(Emp::getDate_of_join)
.thenComparing(Emp::getCity)
.thenComparingInt(Emp::getAge));
编辑:
为了解决评论中的要求,您可以在排序之前根据城市字符串的长度对项目进行排序:
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));