问题描述
我试图在/ attachments文件夹中获取所有未转换的文件,并放入数组,并使用Java字母数字地对未转换的附件数组进行排序。 这是我的代码
// get all non-transformed files in the /attachments folder and put in array
File f = new File("D:\\template_export\\template\\attachments");
ArrayList<String> attachmentFiles = new ArrayList<String>(Arrays.asList(f.list()));
System.out.println("attachmentFiles :" + attachmentFiles);
我需要对以下输出进行排序:
attachmentFiles :[0.gif, 1.gif, 10.gif, 11.gif, 12.gif, 13.gif, 14.gif,
15.gif, 16.gif, 17.gif, 18.gif, 19.gif, 2.gif, 20.gif, 21.gif, 22.gif,
23.gif, 24.gif, 25.gif, 26.gif, 27.gif, 28.gif, 29.gif, 3.gif, 30.html,
31.messages, 32.messages, 4.gif, 5.gif, 6.gif, 7.gif, 8.gif, 9.gif]
我尝试了以下代码:
Collections.sort(attachmentFiles);
for(String counter: attachmentFiles){
System.out.println(counter);
}
但这并没有得到解决。
1楼
需要什么,自定义逻辑对数据列表进行排序。 可能会在下面的解释中帮助您编写相同的内容。
Collections#sort(List<T> list, Comparator<? super T> c)
根据由指定比较器引起的顺序对指定列表进行排序。 列表中的所有元素都必须使用指定的比较器进行相互比较(即c.compare(e1,e2)不得对列表中的任何元素e1和e2抛出ClassCastException。
这就是您可以传递自定义逻辑的方式。
现在如何创建Comparator
逻辑。
范例-
List<String> attachmentFiles = ...;
Collections.sort(attachmentFiles,new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// logic -
//a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second
}
});
2楼
要比较两个不同长度的数字字符串,就好像它们是数字一样,有必要用0个字符填充最短的字符串。
因此,首先必须搜索两个字符串中的第一个点。 比较它们的位置,并用0填充“最短的”数字并用零填充,如以下代码所示。
Collections.sort(attachmentFiles,new Comparator<String>() {
public int compare(String o1, String o2) {
int point1 = o1.indexOf('.');
// If no point is present we assume it is present as last position
if (point1 == -1) {
point1 = o1.length();
}
int point2 = o2.indexOf('.');
// If no point is present we assume it is present as last position
if (point2 == -1) {
point2 = o2.length();
}
if (point1 > point2) {
char[] chars = new char[point1-point2];
Arrays.fill(chars, '0');
o2 = new String(chars) + o2;
} else if (point1 < point2) {
char[] chars = new char[point2-point1];
Arrays.fill(chars, '0');
o1 = new String(chars) + o1;
}
return o1.compareTo(o2);
}
});