我需要使用Java 8 Comparator对 Details 类对象的列表进行排序
Excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
win32c = win32com.client.constants
wb1 = Excel.Workbooks.Open('excel.xlsx')
ws1 = wb1.Worksheets('Sheet1')
cl1 = ws1.Cells(9,2)
cl2 = ws1.Cells(1000,3)
PivotSourceRange = ws1.Range(cl1,cl2)
ws1.Activate()
PivotSourceRange.Select()
cl3 = ws1.Cells(9,2)
PivotTargetRange = ws1.Range(cl3,cl3)
PivotTableName = 'Pivot'
#Make Pivot Table
PivotCache = wb1.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)
PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)
PivotTable.PivotFields('EventDate').Orientation = win32c.xlRowField
PivotTable.PivotFields('EventDate').Position = 1
DataField = PivotTable.AddDataField(PivotTable.PivotFields('Alarm_Backlog'))
chart=ws1.Shapes.AddChart2(201, 51, 300, 100)
wb1.Save()
wb1.Close()
按照“详细信息”类名称的顺序,如下首选项
第一-从字母开始
2nd-从数字开始
and 3rd--以特殊字符开头
预期结果s / b: 排序的详细信息列表=基于“详细信息”名称排序,而不考虑类中的其他参数
class Details{
String name;
String age;
}
"Came"
"result"
"Result came"
"01 Result"
"02 Result"
"05 Result"
"# Came"
"# Result"
答案 0 :(得分:2)
您可以像这样定义自定义优先级
private static int priority(String str){
if (Character.isAlphabetic(string.charAt(0)))return 1;
if (Character.isDigit(string.charAt(0))) return 2;
return 3;
}
然后您可以在比较功能中使用
Collections.sort(list, new Comparator<Project>() {
@Override
public int compare(Details o1, Details o2) {
int result = Integer.compare(priority(o1.name), priority(o2.name));
if (result != 0) return result;
return o1.name.compareTo(o2.name);
}
});
使用Java 8语法
Collections.sort(list,Comparator.comparingInt(d -> priority(d.getName()))
.thenComparing(d-> d.getName()));
答案 1 :(得分:2)
这是Java 11(只需使用var,就这样)代码:
var a = List.of(details1, details2, details3)
.stream()
.sorted(Comparator.comparingInt((Details d) -> priority(d.getName())).thenComparing(Details::getName))
.collect(Collectors.toList());
如果优先级方法难以理解,可以参考@Eklavya的代码
private static int priority(String str){
return Character.isAlphabetic(str.charAt(0))?1:Character.isDigit(str.charAt(0))?2:3;
}