按当前月份到最近六个月对列表<Object> 进行排序

Sort List<Object> by current month to Last six months

我的列表中有以下数据:

    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));

我想做什么?
我正在尝试按顺序对这些数据进行排序,以便数据按月排序,并且该月应从当前月份开始计算前六个月。
例如:
目前是5月份,数据排序应该是这样的:

[MAY, APRIL, MARCH, FEBRUARY, JANUARY, DECEMBER]    

如果缺少任何一个月,它应该跳过它并转到下个月并完成计数。

到目前为止我尝试了什么?

我尝试了以下代码来获取当前月份和前六个月:

        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]

这里是FeatureAnalyzeDTOResultclass供参考:

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();
}

假设当月会得到整数0(或11),然后给每个月分配一个连续的整数。

例如,五月 = 0,六月 = 1,....一月 = 8...

然后,对你的输入数组进行排序,从那里开始,问题就很简单了

我会这样做:

enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
}
public static void main(String[] args) {
    List<String> data = Arrays.asList("october", "april", "march", "november", "may", "january", "december");
    Month currentMonth = Month.MAY;
    List<String> thisYear = data.stream()
                                .filter(a -> Month.valueOf(a.toUpperCase()).ordinal() <= currentMonth.ordinal())
                                .collect(Collectors.toList());
    List<String> lastYear = data.stream()
                                .filter(a -> Month.valueOf(a.toUpperCase()).ordinal() > currentMonth.ordinal())
                                .collect(Collectors.toList());
    Comparator<String> monthComparator = new Comparator<String>() {

        @Override
        public int compare(String a, String b) {    
            Month mA = Month.valueOf(a.toUpperCase());
            Month mB = Month.valueOf(b.toUpperCase());
            return mB.compareTo(mA);
        }
    };
    thisYear.sort(monthComparator);
    lastYear.sort(monthComparator);
    
    thisYear.addAll(lastYear);
    System.out.println(thisYear);
}

你快到了。你缺少的是两件事:

  1. 您忘记过滤掉超过 6 个月前的月份。
  2. 你的比较颠倒了(所以你看到的是升序而不是降序)。

以下同时进行筛选和排序:

    Comparator<FeatureAnalyzeDTOResult> comp =
            Comparator.comparingInt(o -> monthList.indexOf(o.getMonth().toUpperCase()));
    list = list.stream()
            .filter(o -> monthList.contains(o.getMonth().toUpperCase()))
            .sorted(comp)
            .toList();
    System.out.println(list);

输出:

[Feature: may Count: 46 
, Feature: april Count: 46 
, Feature: march Count: 46 
, Feature: january Count: 53 
, Feature: december Count: 30 
]

这里是另一种方法:

  • java.time API
  • Month 枚举中获取月份列表
  • 使用 Collections.rotate 和当前月份值
  • 轮换列表
  • 使用Collections.reverse
  • 反转列表
  • 创建一个比较器来根据上面列表的索引比较月份
  • 流、排序和限制

类似

import java.util.Collections;
import java.util.Comparator;

public static void main(String[] args) {
    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));


    List<Month> months = new ArrayList<>(Arrays.asList(Month.values()));
    Collections.rotate(months, 12 - YearMonth.now().getMonthValue());
    Collections.reverse(months);

    Comparator<FeatureAnalyzeDTOResult> comp =
            Comparator.comparingInt(f -> months.indexOf(Month.valueOf(f.getMonth().toUpperCase())));

    list.stream().sorted(comp).limit(6).forEach(System.out::println);
}