2017-08-13 41 views
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(); 
    } 
} 

谢谢。

+0

使用[TreeSet](https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html) – Oleg

+0

Oleg:TreeSet删除重复项!也许我的帖子是不够清晰,我仍然希望重复 –

+0

好吧,检查此链接https://stackoverflow.com/questions/8819550/efficiently-ordered-data-structure-that-supports-duplicate-keys – Oleg

回答

1

我认为实施Iterable不是最好的方法,因为你应该更喜欢构图而不是继承,毕竟它是2017年;没有人再实现自己的集合类。这就是说,以下情况如何?

public class Main { 

    public static void main(String[] args) throws IOException, URISyntaxException { 
     for (String line : new FileSorter(new File(Main.class.getResource("test.txt").toURI()).toPath())) { 
      System.out.println(line); 
     } 
    } 

    static class FileSorter implements Iterable<String> { 
     private final Path path; 

     FileSorter(Path path) { 
      this.path = path; 
     } 

     @Override 
     public Iterator<String> iterator() { 
      try { 
       return Files.lines(path) 
         .sorted() 
         .iterator(); 
      } catch (IOException e) { 
       throw new UncheckedIOException(e); 
      } 
     } 
    } 
} 

给出一个文件test.txt在同一个目录作为类Main

a 
b 
a 
c 

上述程序打印:

a 
a 
b 
c 

Iterable具有不同的语义比Stream,因为前者可以重复使用,而后者只能使用一次(直到终端操作)。因此,我的实现在每次拨打iterator()时都会读取文件。我没有试图优化它,因为你没有要求它,过早的优化是所有邪恶的根源。

相关问题