我的列表中有以下数据:
List<FeatureAnalyzeDTOResult> list = new ArrayList<>();
list.add(new FeatureAnalyzeDTOResult("october", 46));
list.add(new FeatureAnalyzeDTOResult("april", 46));
list.add(new FeatureAnalyzeDTOResult("march", 46));
list.add(new FeatureAnalyzeDTOResult("november", 30));
list.add(new FeatureAnalyzeDTOResult("may", 46));
list.add(new FeatureAnalyzeDTOResult("january", 53));
list.add(new FeatureAnalyzeDTOResult("december", 30));
What am I trying to do?
I am trying to sort this data in a sequence such that the data is sorted by month and the month should start from the current month and count the previous six months.
For example:
Currently, it is May, and the data should be sorted in the following order:
[MAY, APRIL, MARCH, FEBRUARY, JANUARY, DECEMBER]
如果缺了任何一个月,它应该直接跳过它,转到下一个月,并完成计数.
What I have tried so far?
我try 了以下代码来获取当前月份和之前的六个月:
YearMonth thisMonth = YearMonth.now();
String[] month = new String[6];
for (int i = 0; i < 6; i++) {
YearMonth lastMonth = thisMonth.minusMonths(i);
DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("MMMM");
month[i] = lastMonth.format(monthYearFormatter);
month[i] = month[i].toUpperCase();
}
List<String> monthList = Arrays.asList(month);
System.out.println(monthList);
我也试着写了一个Comparator
,但并没有达到预期效果.我对写Comparator
的逻辑有点困惑.
Comparator<FeatureAnalyzeDTOResult> comp = (o1, o2)
-> monthList.indexOf(o2.getMonth().toUpperCase()) - monthList.indexOf(o1.getMonth().toUpperCase());
list.sort(comp);
它给出如下输出:
[Feature: december Count: 30
, Feature: january Count: 53
, Feature: march Count: 46
, Feature: april Count: 46
, Feature: may Count: 46
, Feature: october Count: 46
, Feature: november Count: 30]
以下是FeatureAnalyzeDTOResult
级课程供参考:
class FeatureAnalyzeDTOResult {
private String month;
private int count;
public FeatureAnalyzeDTOResult(String feature, int count) {
this.month = feature;
this.count = count;
}
public FeatureAnalyzeDTOResult() {
}
public String getMonth() {
return month;
}
public void setMonth(String feature) {
this.month = feature;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
StringBuilder string = new StringBuilder();
string.append("Feature: ").append(getMonth()).append(" Count: ").append(getCount()).append(" \n");
return string.toString();
}