java - 使用列表作为值

时间:2016-10-18 14:34:02

标签: java string collections frameworks

我有一个.txt:

  1. line:x,Munich,c,e,f
  2. line:y,Berlin,ad,uf
  3. line:z,Hamburg,of,bf
  4. 所有单词都以','

    分隔

    此txt中一行的前两个字符串转到构造函数。 3.及以下字符串转到List。 例如,关键是:b是构造函数的形式 该值是一个ArrayList,其中包含:c,e,f。所以3个元素。

    String filePath = "....txt";
    
            List<String> itemlist = new ArrayList<String>();
            HashMap<Corporation, List> corp = new HashMap<Corporation, List>();
    
            String line;
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",", 3);
                if (parts.length >= 3) {
                    String name = parts[0]; // key=name, value= address
                    String address = parts[1];
                    String info = parts[2];
                    itemlist = new ArrayList<String>(Arrays.asList(info.split(",")));
                    Corporation cor = new Corporation(name, address);
                    corp.put(cor, itemlist);
                }
            }
    

    一切正常。 现在我需要在Map中的一个ArrayLists中搜索一个字符串。 例如,我搜索字符串&#34; bf&#34;并打印出它找到的字符串以及地图右键的位置。例如,使用&#34; bf&#34;:它将打印&#34; bf发现在&#34; z,汉堡&#34;&#34;。

    for (Entry<Corporation, List> entry : corp.entrySet()) {
                if (entry.getValue().equals("bf")) {
                    System.out.println("Found at " + );
                    System.out.println(entry.getKey());
                } else {
                    System.out.println("String not found.");
                }
            }
    

    这部分代码无法正常工作。我该怎么做?

2 个答案:

答案 0 :(得分:1)

if (entry.getValue().equals("bf"))正在将ListString进行比较。

试试这个if (entry.getValue().contains("bf"))

答案 1 :(得分:0)

entry.getValue().equals("bf")

比较List与String。这永远不会成真。

你最有可能想到这个:

entry.getValue().contains("bf")