2个字符串文件的交集 - java

时间:2013-12-08 16:29:03

标签: java string intersection

我有2个带字符串行的文件,我必须找到属于这两个文件的行数。

我该怎么办?

例如 - 文件1:

aaa 
bbb
ccc

file2的:

bbb
eee
aaa

结果应为2

3 个答案:

答案 0 :(得分:2)

您将文件1中的所有行读入Set,然后检查它是否已包含来自file2的行:

 Set<String> linesFile1 = ... read in your lines
 for (String line : file2) {  // add each line from file2 and check if it was already in the set
    if (linesFile1.contains(line)) {
         counter++;
    }
 }

答案 1 :(得分:0)

对交叉点使用retainAll(..)操作,

 Set<String> aSet=new HashSet(Arrays.asList("aaa", "bbb", "ccc"));
 Set<String> bSet=new HashSet(Arrays.asList( "bbb", "eee","aaa"));

 aSet.retainAll(bSet);//This will do the intersection operation between two Set

 System.out.println(aSet.size());

答案 2 :(得分:0)

基本算法

1. Read all lines from file1 and add it into Set1
2. Read all lines from file2 and add it into Set2
3. Then use Guava's intersection method to obtain a new intersection Set
4. Print out the size of the intersection set.

Guava's intersection method