如何概括 Java 8 中 excel 的 .thenby 的实现?

How to generalize the implementation the .thenby of excel in Java 8?

我有以下服务class:

public class SheetSorter {

    // sorts the sheet
    public static Sheet sortSheet(Sheet sheet) {
        List<String[]> list = sheet.getSheet().stream().collect(Collectors.toList());
        Collections.sort(list, new Comparator<String[]>() {
            @Override
            public int compare(String[] arr1, String[] arr2) {
                if (Long.parseLong(arr1[3]) == Long.parseLong(arr2[3])) {
                    return (int) (Long.parseLong(arr1[4]) - Long.parseLong(arr2[4]));
                }
                else {
                    return (int) (Long.parseLong(arr1[3]) - Long.parseLong(arr2[3]));
                }
            }
        });
        sheet.setSheet(list);
        return sheet;
    }
}

如您所见,sortSheet 方法在 column 4 上实现 sort,在 column 5 上实现 thenby。有什么方法可以将其转换为采用 Integer... columnOrder 作为参数,以便 运行 对 columnOrder[0] 和 'thenBies' 进行排序(还是 'thenBys'? ) 按该顺序提供的其余参数?


编辑:

@Holger的建议

// sorts the sheet
public static Sheet sortSheet(Sheet sheet) {
    List<String[]> list = new ArrayList<>(sheet.getSheet());
    Collections.sort(list, new Comparator<String[]>() {
        
        @Override
        public int compare(String[] arr1, String[] arr2) {
            if (Long.parseLong(arr1[3]) == Long.parseLong(arr2[3])) {
                return Long.compare(Long.parseLong(arr1[4]), Long.parseLong(arr2[4]));
            }
            else {
                return Long.compare(Long.parseLong(arr1[3]), Long.parseLong(arr2[3]));
            }
        }
    });
    sheet.setSheet(list);
    return sheet;
}

一种简单的方法是根据 int 数组编写 Comparator

public static Sheet sortSheet(Sheet sheet, int...indices) {
    
    if(indices.length == 0) throw new IllegalArgumentException();
    
    Comparator<String[]> comp = Comparator.comparingLong(s -> Long.parseLong(s[indices[0]]));
    for(int i = 1; i < indices.length; i++) {
        int e = i;
        comp = comp.thenComparing(Comparator.comparingLong(s -> Long.parseLong(s[indices[e]])));
    }
    
    List<String[]> list = sheet.getSheet().stream().collect(Collectors.toList());
    Collections.sort(list, comp);
    sheet.setSheet(list);
    
    return sheet;
}
上面的

comp 是根据 indices[0].

之后的索引组合其他 Comparator 创建的

我基于已接受答案的解决方案:

public static Sheet sortSheet(Sheet sheet, Integer... indices) {

    List<String[]> list = new ArrayList<>(sheet.getSheet());
    Collections.sort(list, new Comparator<String[]>() {
        
        @Override
        public int compare(String[] arr1, String[] arr2) {
            for (int i = 0; i < indices.length;) {
                if (Long.parseLong(arr1[i]) == Long.parseLong(arr2[i])) {
                    i++;
                }
                else {
                    return Long.compare(Long.parseLong(arr1[i]), Long.parseLong(arr2[i]));
                }
            }
            return 0;
        }
    });
    sheet.setSheet(list);
    return sheet;
}