繁体   English   中英

如何搜索一个列表中的 en 元素是否存在于另一个列表中的元素中,然后打印该元素

[英]How can I search if en element from one List exists in the elements in the other list and then print this element

我有一个从属性文件中读取的字符串元素列表,然后返回这些元素的列表:

public static ArrayList<String> getExpextedTestDataForHeaderList() throws IOException {
    ArrayList<String> testDataList = new ArrayList<String>();

    testDataList.add(hpExpectedTxtStoiximaBtn());
    testDataList.add(hpExpectedTxtLiveStoiximaBtn());
    testDataList.add(hpExpectedTxtVirtualBtn());
    testDataList.add(hpExpectedTxtCasinoBtn());
    testDataList.add(hpExpectedTxtLiveCasinoBtn());
    testDataList.add(hpExpectedTxtOtherGamesBtn());
    testDataList.add(hpExpectedTxtLogInBtn());
    testDataList.add(hpExpectedTxtRegisterBtn());


    for (int i = 0; i < testDataList.size(); i++) {
        String actualTitle = testDataList.get(i).toString();
        //System.out.println("From File: "+actualTitle);
    }
    return testDataList;
}

然后我有一个方法来获取元素( getElementsNames )并将它们转换为第二个列表

private static ArrayList<String> methodConvertElementToList(String path) {
    ArrayList<String> list = getElementsNames(path);
    for (int i = 0; i < list.size(); i++) {
        return list;
    }
    return list;
}

到目前为止,当我执行我的程序时,我得到了 2 个包含元素的列表。

现在,如果包含第一个列表的元素,我如何从第二个列表中搜索,然后在屏幕上打印这些元素?

我想出了一些代码,但它不起作用。 有人能帮忙吗?

public static void printToScreen(String path,List<String> expectedDataList) throws IOException {
    ArrayList<String> expectedNames = (ArrayList<String>) expectedDataList;
    ArrayList<String> actualNames = getElementsNames(path);
    //ListIterator<String> expectedNamesListIterator = expectedNames.listIterator();
    //ListIterator<String> actualNamesListIterator = actualNames.listIterator();
}

使用迭代器? 还是其他方式?

如果我理解正确,您可以简单地使用listA.containsAll(listB)示例代码,如下所示

List<String> listA = new ArrayList<>(
            List.of("ala",
                    "adam",
                    "bocian",
                    "hello",
                    "world"));

List<String> listB = new ArrayList<>(
            List.of("ala",
                    "hello"));

if(listA.containsAll(listB)){
    System.out.println("YOUR CODE");
}

如果 listB 的所有元素都存在于 listA 中,则返回 true,那么您可以简单地打印 listB 的所有元素。

其他方式,如果您不想检查所有元素,您可以获取 listA 的单个元素并检查它是否存在于 listB

listA.stream()
            .filter(listB::contains)
            .forEach(System.out::println);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM