[Java problem integration]Java l
Java中, 对List的排序也是非常常用的,对于一般类型如String,可以直接调用List.sort()方法,并传入java.util.Comparator的实现的对象
List<String> strList = new ArrayList<>();
strList.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
当List里面存储的是一些自定义的POJO或者复杂对象时,如果在每次排序时都去实现一次java.util.Comparator,个人觉得十分麻烦。
这里例如有一个POJO类Person,
public class Person{
private String name;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
并有LIst<Person> persons=new ArrayList<>();并按name 和 birthday排序。可以定义两个接口
public interface ISortDateOption {
public Date getSortDateField();
}
public interface ISortStringOption {
public String getSortStringField();
}
并定义对应的Comparator类如下
public class CommonDateComparator implements Comparator<ISortDateOption> {
@Override
public int compare(ISortDateOption o1, ISortDateOption o2) {
return o1.getSortDateField().before(o2.getSortDateField())?1:-1;
}
}
public class CommonStringComparator implements Comparator<ISortStringOption> {
@Override
public int compare(ISortStringOption o1, ISortStringOption o2) {
return o1.getSortStringField().compareTo(o2.getSortStringField());
}
}
让前文的Person实现两个接口
public class Person implements ISortStringOption, ISortDateOption{
...//原代码略
@Override
public String getSortField() {
return this.name == null ? "" : this.name;
}
@Override
public Date getSortDateField() {
return this.getBirthday();
}
}
这样persons按name排序时调用persons.sort(new CommonStringComparator());按birthday排序时调用persons.sort(new CommonDateComparator());便可