List先按一个字段分类再按一个字段比较大小的方法

核心代码:

Comparator<FieldDiff> byCategory = Comparator.comparing(FieldDiff::getFieldCategory, Comparator.nullsLast(String::compareTo));
Collections.sort(fieldDiffs, byCategory.thenComparingInt(FieldDiff::getDisplayOrder));

使用方法:

@Test
public void test() throws IOException {
    List<FieldDiff> fieldDiffs = Lists.newArrayList();
    FieldDiff diff = new FieldDiff();
    diff.setFieldCategory("03.基础");
    diff.setDisplayOrder(10);
    fieldDiffs.add(diff);

    diff = new FieldDiff();
    diff.setFieldCategory("02.规格族");
    diff.setDisplayOrder(5);
    fieldDiffs.add(diff);

    diff = new FieldDiff();
    diff.setFieldCategory("01.规格族");
    diff.setDisplayOrder(1);
    fieldDiffs.add(diff);

    Comparator<FieldDiff> byCategory = Comparator.comparing(FieldDiff::getFieldCategory, Comparator.nullsLast(String::compareTo));
    Collections.sort(fieldDiffs, byCategory.thenComparingInt(FieldDiff::getDisplayOrder));

    System.out.println(fieldDiffs);
    
}

输出:

posted @ 2023-04-11 17:30  xlfdy  阅读(26)  评论(0编辑  收藏  举报