嗨,我正在尝试比较两个arrayLists。像这样:

public class intersection {
 public static void main(String... args) throws Exception {

    List<String> list1 = new ArrayList<String>(Arrays.asList("This is a test example to help me learn hashsets"));
    List<String> list2 = new ArrayList<String>(Arrays.asList("test example", "Not returned"));

    System.out.println(new intersection().intersection(list1, list2));

}


public <T> List<T> intersection(List<T> list1, List<T> list2) {
    List<T> list = new ArrayList<T>();

    for (T t : list1) {
        if(list2.contains(t)) {
            list.add(t);
        }
    }

    return list;
}
}


我希望返回“测试示例”,因为它位于两个arrayLists中的某处。对不起,忘了说不能更改arrayLists的内容吗?谢谢

最佳答案

您要么需要检查单个单词

public class intersection {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("This is a test example to help me learn hashsets".split("\\s+")));
        List<String> list2 = new ArrayList<String>(Arrays.asList("test example Not returned".split("\\s+")));

        System.out.println(new intersection().check(list1, list2));

    }

    public <T> List<T> check(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if (list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
}


或者,您可以选择在整个字符串中搜索短语

公共类交叉点{

public static void main(String... args) throws Exception {

    String s1 = "This is a test example to help me learn hashsets";
    String[] s2 = new String[] { "test example", "Not returned" };

    System.out.println(new intersection().check(s1, s2));

}

public List<String> check(String s1, String[] s2) {
    List<String> list = new ArrayList<>();

    for (String s : s2) {
        if (s1.contains(s)) {
            list.add(s);
        }
    }

    return list;
}


}

09-11 19:30