2
我想知道在Java集合中对file.txt行进行排序的最佳方法。PriorityQueue和ArrayList更好地结合在一起?
使用orderedSet删除重复,我不希望这样。
PriorityQueue完成这项工作,但我需要我的类是Iterable,并且使用PriorityQueue.Iterator不会给出排序结果。
现在我很困惑使用Arrays.sort或使用这种方法: 使用PriorityQueue时,从文本读取行,然后复制数组的最后一个队列使用它的迭代器?
public class FileSorter implements Iterable<String> {
// this sorted set contains the lines
private PriorityQueue<String> lines0 = new PriorityQueue<>() ;
private ArrayList<String> lines = new ArrayList<>();
public void readFiles (String[] filePaths) throws IOException {
BufferedReader buf = null;
String line ;
for (String path:filePaths) {
//opening the file
buf = new BufferedReader(new FileReader(new File(path)));
//iterating through the lines and adding them the collection
while ((line = buf.readLine()) != null) {
if(line.trim().length() > 0) { //no blank lines
lines0.add(line);
}
}
};
//closing the buffer
buf.close();
while (!lines0.isEmpty()){
lines.add(lines0.poll());
}
}
public Iterator<String> iterator() {
return lines.iterator();
}
}
谢谢。
使用[TreeSet](https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html) – Oleg
Oleg:TreeSet删除重复项!也许我的帖子是不够清晰,我仍然希望重复 –
好吧,检查此链接https://stackoverflow.com/questions/8819550/efficiently-ordered-data-structure-that-supports-duplicate-keys – Oleg