首页 > 解决方案 > 如何在一个哈希图中读取两个大文本文件

问题描述

我有两个文本文件

     file1. txt                file2.txt

  http://example.com       http://example.com
  http://example.com       http://example.com

我想逐行读取这两个文件并比较两者的输出。像 file1 的 line1 输出和 file2 的 line1 输出

那么,如果这两个文件有数百万行,我们如何才能有效地读取它们。

我们可以使用 java lambda 表达式吗?

标签: javafiledata-structureslambdatime-complexity

解决方案


private static <R> List<R> compare(Path path1, Path path2, BiFunction<String, String, R> compare) throws IOException
{
    List<R> list = new ArrayList<>();
    try (Stream<String> s1 = Files.lines(path1);
         Stream<String> s2 = Files.lines(path2))
    {
        Iterator<String> itr1 = s1.iterator();
        Iterator<String> itr2 = s2.iterator();
        //compare only till both the files have some entry
        while (itr1.hasNext() && itr2.hasNext())
        {
            list.add(compare.apply(itr1.next(), itr2.next()));
        }
    }
    return list;
}

推荐阅读