I am having the following data in my list:
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]
And if any month is missing, it should simply skip it and go for the next month and should complete the count.
What I have tried so far?
I have tried the following code to get the current month and the preceding six months:
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);
I have also tried writing a Comparator but it is not working as expected. I am a bit confused with the logic to write the Comparator.
Comparator<FeatureAnalyzeDTOResult> comp = (o1, o2)
-> monthList.indexOf(o2.getMonth().toUpperCase()) - monthList.indexOf(o1.getMonth().toUpperCase());
list.sort(comp);
It gives the output as follows:
[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]
Here is the FeatureAnalyzeDTOResult class for reference:
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();
}