public class record {
//状态
private string state;
//时长
private string time;
public record(string state, string time) {
this.state = state;
this.time = time;
}
public string getstate() {
return state;
}
public string gettime() {
return time;
}
@override
public string tostring() {
return "record{" +
"state='" + state + '\'' +
", time='" + time + '\'' +
'}';
}
}
比较器 a:先对【状态】排序,然后再对【时长】按正序排序
public class recordcomparator implements comparator<record> {
@override
public int compare(record o1, record o2) {
final int statecompare = o1.getstate().compareto(o2.getstate());
if (statecompare == 0) {
return o1.gettime().compareto(o2.gettime());
}
return statecompare;
}
}
比较器 b:先对【状态】排序,然后再对【时长】按逆序(倒序)排序
public class recordtimedesccomparator implements comparator<record> {
@override
public int compare(record o1, record o2) {
final int statecompare = o1.getstate().compareto(o2.getstate());
if (statecompare == 0) {
return o2.gettime().compareto(o1.gettime());
}
return statecompare;
}
}
单元测试:
record record1 = new record("通话中", "00:01:08");
record record2 = new record("空闲", "00:18:02");
record record3 = new record("通话中", "00:04:04");
record record4 = new record("空闲", "00:01:57");
list<record> recordlist = new arraylist<>();
recordlist.add(record1);
recordlist.add(record2);
recordlist.add(record3);
recordlist.add(record4);
system.out.println("排序前:" + recordlist);
collections.sort(recordlist, new recordcomparator());
system.out.println("排序后【时间正序】:" + recordlist);
recordlist = new arraylist<>();
recordlist.add(record1);
recordlist.add(record2);
recordlist.add(record3);
recordlist.add(record4);
system.out.println("排序前:" + recordlist);
collections.sort(recordlist, new recordtimedesccomparator());
system.out.println("排序后【时间倒序】:" + recordlist);