【问题标题】:Find the intersection of two Strings找到两个字符串的交集
【发布时间】:2015-12-08 02:18:53
【问题描述】:

我有两个 CSV 文件:“userfeatures”和“itemfeatures”。

我应该将每一行 userfeatures 与每一行 itemfeatures 进行比较,以找到每行的匹配项(交叉点)。 比如userfeature文件的第一行是:

005c2e08","Action","nm0000148","dir_ nm0764316","India"

现在,我需要找到此行(与 user-1 相关)与第二个文件“itemfeatures”的每一行的交点。第二个文件具有相同的结构,例如,第一个比较将与“itemfeatures”的第一行,即:

"tt0306047","Comedy","nm0267506,nm0000221,nm0356021","dir_ nm0001878","USA,Canada"

这是我迄今为止尝试过的:

public class Main {
      public static void main(String[] args) throws Exception {   
         BufferedReader userfeatures = new BufferedReader(new FileReader("userfeatures.csv"));
         BufferedReader itemfeatures = new BufferedReader(new FileReader("itemfeatures.csv"));       
         ArrayList<String> userlines = new ArrayList<>();
         ArrayList<String> itemlines = new ArrayList<>();
         String Uline = null;
         String Iline = null;

         while ((Uline = userfeatures.readLine()) != null) {
                for (int i=1; i< userlines.size(); i++){
                   userlines.add(Uline); 
                   intersect(Uline, Iline).size();
                }
        }
     //  System.out.println(Uline);    
     userfeatures.close();
     itemfeatures.close();
     }       
      static ArrayList<String> intersect(String Uline, String Iline) {
           ArrayList<String> result = new ArrayList<String>();
           result.retainAll(Iline);
           return result;
        }
    }

似乎我不能对“String”类型使用retainAll,所以我想知道如何解决这个问题?我在这里搜索了很多,但我发现的只是寻找数组的交集,除了this one。 (但这篇文章与我的情况不同,因为它比较了字符串中的每个字符,而我需要逐字比较)。

【问题讨论】:

标签: java string arraylist


【解决方案1】:

尝试将UlineIline转换成单词,改用Set&lt;String&gt;而不是Array&lt;String&gt;

static Set<String> intersect(String Uline, String Iline) {
    Set<String> result = new HashSet<String>(Arrays.asList(Uline.split(",")));
    Set<String> IlineSet = new HashSet<String>(Arrays.asList(Iline.split(",")));
    result.retainAll(IlineSet);
    return result;
}

【讨论】:

    【解决方案2】:

    首先,将行拆分为数组。然后,在非空数组上调用retainAll

    【讨论】:

    • 感谢您的回答。但我认为这些行已经是字符串数组,因为当我打印 itemlines.get(1) 时,我得到了这个:"tt0002199","Drama,Biography","nm0376639,nm0245769,nm0310155","dir_ nm0646058","USA" 这是一个字符串数组..我错过了什么吗?
    • 对不起,我的意思是这一行也应该被方法相交中的cvs分隔符分割。 @Jerry06 提到的这种方法。
    • 谢谢,我尝试了 Jerry 的回复,但是,我仍然有一些错误.. 我想我也应该修复这部分 intersect(Uline, Iline).size(); 因为我只是注意到此刻我想计算 intersect Iline是空的..我也应该读一下...
    • 也许值得单独阅读这些文件的内容,因为它的行数可以不同。在这样的操作之后,您将通过两个功能内容的所有行进行简单的双循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多