2 回答
TA贡献1828条经验 获得超3个赞
尝试这样的事情:
public ArrayList<Item> sort(List<Item> list) {
ArrayList<Item> dateSort= new ArrayList<>();
ArrayList<Item> result = new ArrayList<>();
if (list!= null && list.size() != 0) {
dateSort= new ArrayList<>(list);
Collections.sort(
dateSort, (o1, o2) -> Integer.compare(o1.getIntDate(), o2.getIntDate()));
int currentDate = dateSort.get(0).getIntDate();
ArrayList<Item> temp= new ArrayList<>();
for (int i = 1; i < dateSort.size(); i++) {
if (dateSort.get(i).getIntDate() > currentDate ) {
currentDate = dateSort.get(i).getIntDate();
result.addAll(timeSort(temp));
temp.clear();
temp.add(dateSort.get(i));
}
else{
temp.add(dateSort.get(i));
}
}
}
return result;
}
private ArrayList<Item> timeSort(List<Item> list) {
ArrayList<Item> timeSort= new ArrayList<>();
if (list!= null && list.size() != 0) {
timeSort= new ArrayList<>(list);
Collections.sort(
timeSort, (o1, o2) -> Integer.compare(o1.getIntTime(), o2.getIntTime()));
}
return timeSort;
}
TA贡献1862条经验 获得超7个赞
我创建了以下示例,
public class Timings {
private LocalDate date;
private int hour;
public Timings(LocalDate date, int hour) {
this.date = date;
this.hour = hour;
}
public LocalDate getDate() {
return date;
}
public int getHour() {
return hour;
}
@Override
public String toString() {
return "Timings{" +
"date=" + date +
", hour=" + hour +
'}';
}
}
public class Sorting {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2015, 02, 20);
LocalDate date1 = LocalDate.of(2018, 07, 12);
LocalDate date2 = LocalDate.of(2017, 05, 10);
Timings timings = new Timings(date, 10);
Timings timings1 = new Timings(date1, 8);
Timings timings2 = new Timings(date2, 12);
List<Timings> dateList = List.of(timings, timings1, timings2);
List<Timings> newList = dateList.stream()
.sorted( (a1, a2) -> a1.getDate().compareTo(a2.getDate()))
.sorted(Comparator.comparingInt(Timings::getHour))
.collect(Collectors.toList());
System.out.printf(newList);
}
}
在上面,第一种排序方法负责根据日期进行排序。第二个按小时照顾。
我得到以下输出
[Timings{date=2018-07-12, hour=8}, Timings{date=2015-02-20, hour=10}, Timings{date=2017-05-10, hour=12}]
添加回答
举报