[英]sorting objects into an array of elements and an array with several elements
[英]sorting elements File[] array
我正在尝试对fList
数组中的文件名进行排序。 最初fList
是这样排序的https://i.stack.imgur.com/OCqJR.jpg和结果https://i.stack.imgur.com/GGBsq.jpg
我希望结果按照文件名之前的数字排序,如下所示:
...
我有something()
方法可以从fList[x]
文件名中获取数字,以便稍后在执行swap(fList[x], fList[y])
时进行比较swap(fList[x], fList[y])
正如您从输出控制台所看到的那样。 我不确定我是否理解File[]
实际上是如何存储和更改其元素的
public static void main(String[] args) {
File file = new File("pathToFolder");
File[] fList = file.listFiles();
for(int x = 0; x < fList.length; x++) {
int numberX = something(fList[x]);
for(int y = x; y < fList.length; y++) {
int numberY = something(fList[y]);
if(numberX > numberY) {
File temp = fList[x];
fList[x] = fList[y];
fList[y] = temp;
}
}
}
for(int x = 0; x < fList.length; x++) {
System.out.println(fList[x].getName());
}
}
static int something(File file) {
String temp = file.getName();
String number = "";
for(int st = 0; st < temp.length(); st++) {
if(temp.charAt(st) == '.') break;
number += temp.charAt(st);
}
int fileNumber = Integer.parseInt(number);
return fileNumber;
}
如果您使用的是Java8
试试这个,您当然可以调整它以满足您的要求:
List<File> sortedFiles = stream(requireNonNull(file.listFiles()))
.sorted(File::compareTo)
.collect(toList());
您还可以使用类Arrays
提供的sort
方法:
File[] sortedFiles = file.listFiles();
// One liner
Arrays.sort(sortedFiles);
这两种解决方案都依赖于
File
类中compareTo
的实现。 官方文档的链接。
我在我的个人git repo 中添加了一个测试
下面的代码怎么样:
public static void main(String[] args) {
File file = new File("pathToFolder");
File[] fList = file.listFiles();
Map<Integer, File> fileMap = new TreeMap<Integer, File>();
for (int x = 0; x < fList.length; x++) {
int numberX = something(fList[x]);
fileMap.put(numberX, fList[x]);
}
fileMap.forEach((k, v) -> System.out.println((v.getName())));
}
static int something(File file) {
String temp = file.getName();
String number = temp.split("\\.")[0];
int fileNumber = Integer.parseInt(number);
return fileNumber;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.