[英]More efficient sorting for pairs of files
I have a folder with pairs of files. 我有一个包含成对文件的文件夹。 Pairs share filename but have different extension (in this case, they are pairs of .txt and .png).
成对共享文件名,但是具有不同的扩展名(在这种情况下,它们是成对的.txt和.png)。 I am looking to store them into a HashMap< File, File > by pairs.
我正在将它们成对存储到HashMap <File,File>中。 Here is what I did to find the pairs:
这是我找到配对的方法:
LinkedList<File> fileList = new LinkedList<File>(Arrays.asList(fileArray));
LinkedList<File> alreadyCompared = new LinkedList<File>();
HashMap<File, File> filePairs = new HashMap<File, File>();
for (Iterator<File> itr1 = fileList.iterator(); itr1.hasNext(); ) {
File comparator = itr1.next();
if (!alreadyCompared.contains(comparator)) {
String stringComparator = comparator.getName().split("\\.")[0];
alreadyCompared.add(comparator);
for (Iterator<File> itr2 = fileList.iterator(); itr2.hasNext(); ) {
File compared = itr2.next();
if (!alreadyCompared.contains(compared)) {
String stringCompared = compared.getName().split("\\.")[0];
if (stringComparator.equals(stringCompared)) {
if (comparator.getName().endsWith("txt")) {
filePairs.put(comparator, compared);
} else {
filePairs.put(compared, comparator);
}
}
}
}
}
}
return filePairs;
Now, this takes a lot of time when I have more than 1000 files to sort, and I'd like to find a more efficient way of doing it. 现在,当我要排序的文件超过1000个时,这将花费大量时间 ,并且我想找到一种更有效的方式来进行排序。 What other way can I sort these files?
我还可以通过哪些其他方式对这些文件进行排序?
Thanks a lot! 非常感谢!
Instead of putting them in an unordered Map
like HashMap
, I would put the elements in a TreeMap
because it sorts it's keys. 与其将它们放在像
HashMap
这样的无序Map
,我不将元素放在TreeMap
因为它对键进行排序。
Per the linked Javadoc, 根据链接的Javadoc,
A Red-Black tree based
NavigableMap
implementation.基于红黑树的
NavigableMap
实现。 The map is sorted according to the natural ordering of its keys, or by aComparator
provided at map creation time, depending on which constructor is used.根据映射键的自然顺序或在映射创建时提供的
Comparator
对映射进行排序,具体取决于所使用的构造函数。
I made up a bit of code to illustrate my comment. 我编写了一些代码来说明我的评论。
HashMap<File, File> filePairs = new HashMap<File, File>();
File dir = new File("your files directory");
File [] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
String fileName = "";
for (File txtFile : files) {
fileName = txtfile.getName().split("\\.")[0];
pngFile = new File(dir.getAbsolutePath() + fileName + ".png");
if (pngFile.exists()) {
filePairs.put(txtFile, pngFile);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.