【问题标题】:How can I get the List (Search) to tell me whether or not each it is in the other List (main)?我怎样才能让列表(搜索)告诉我它是否在另一个列表(主)中?
【发布时间】:2018-10-10 15:57:38
【问题描述】:

我正在尝试比较文件读取的两个文本文件中的列表项

Black 10
Brown 22
Orange 29
Red 7
Silver 15
Tan 17
White 0
Yellow 20
Aqua 15
Orange 12
Blue 3
Silver 30

搜索文件读取

Brown 22
Silver 30
White 10
Blue 3
Blue 13
Yellow 20
Orange 22
Orange 90

我希望它打印出如下内容:

 Brown 22 found in file
 Orange 29 no found in file etc..

到目前为止,我有这个,它只是打印出 2 并告诉你它是什么,我似乎无法找到比较两者的方法,并告诉我是否找到了主要项目搜索项目

 public static void main(String args[]) throws IOException {  
   String token1 = "";
   String token2 = "";
   Scanner inFile1 = new Scanner(new FileReader("Lab2InputFile1.txt")).useDelimiter(",\\s");
   Scanner inFile2 = new Scanner (new FileReader("Lab2InputFile2.txt")).useDelimiter(",\\s");;
   List <String> temp1 = new ArrayList<String>();
   List <String> temp2 = new ArrayList<String>();
   while (inFile1.hasNext()) {
       token1 = inFile1.next();
       temp1.add(token1);
    }
    System.out.println("Main Items are" );
    inFile1.close();
    String [] MainItems = temp1.toArray(new String[0]);
    for (String s: MainItems) {
        System.out.println(s);
    }
    while (inFile2.hasNext()) {
        token2 = inFile2.next();
        temp2.add(token2);
    }
    System.out.println ("Search Items are");
    inFile2.close();
    String [] SearchItems = temp2.toArray(new String [0]);
    for (String t : SearchItems) {
        System.out.println(t);
    }

【问题讨论】:

  • 无需将列表更改为数组。遍历temp1 并查看temp1 元素是否存在于temp2 中的某处。请参阅List.contains() 方法。
  • 您是否将Black 10 存储为列表中的一个元素?
  • 是的,我只是将它用作单个字符串

标签: java string list arraylist


【解决方案1】:
    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();

    for (String item : list1) {
        if (list2.contains(item)) {
            System.out.println(item + " found in file");
        } else {
            System.out.println(item + " not found in file");
        }
    }

【讨论】:

    【解决方案2】:

    遍历seach array 并检查source array 是否包含。

    在这种情况下使用contains 方法。

    希望对你有帮助

    List<String> source = Arrays.asList("Item 1", "Item 2", "Item 3");
    List<String> search = Arrays.asList("Item 1", "Item 4");
    search.stream().forEach(s -> {
        if (source.contains(s)) {
            System.out.println(s + " found in file");
        } else {
            System.out.println(s + " not found in file");
        }
    });
    

    结果

    • 在文件中找到第 1 项
    • 文件中未找到第 4 项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 2021-08-03
      • 2012-08-31
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多