简体   繁体   English

使用集合和映射读取文本文件

[英]Using sets and maps to read text files

As part of my HOMEWORK, I am trying to read a file made up of car models and output the total of each to the console. 作为我的家庭作业的一部分,我试图读取一个由汽车模型组成的文件,并将每个模型的总和输出到控制台。

I have achieved this so far by using a Map with the model name as the key and the counter as the value. 到目前为止,我已经通过使用以模型名称作为键和以计数器作为值的Map实现了这一目标。

Although, now I want to only output models that are added to a Set. 虽然,现在我只想输出添加到Set中的模型。 So, if Fiat was in the file, it wouldnt be used as it is not in the allowable Set. 因此,如果菲亚特在文件中,则不会使用它,因为它不在允许的集合中。

Hopefully that makes sense and help is appreciated. 希望这是有道理的,并感谢您的帮助。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Test 
{

public static void main(String[] args) throws FileNotFoundException 
{
    TreeMap<String, Integer> map = new TreeMap<String, Integer>();
    Set<String> fruit = new TreeSet<String>();
    fruit.add("BMW");
    fruit.add("Mercedes");
    fruit.add("Ford");
    fruit.add("Nissan");
    fruit.add("Tesla");

    File inputFile = new File("input.txt");
    Scanner in = new Scanner(inputFile);

    while (in.hasNext()) 
    {
        String word = in.next();
        if (map.containsKey(word))
        {
            int count = map.get(word) + 1;
            map.put(word,  count);
        }
        else
        {
            map.put(word,  1);
        }
    }
    in.close();

    for (Map.Entry<String, Integer> entry : map.entrySet())
    {
        System.out.println(entry);
    }
  }
}

You could just iterate through your set and then invoke the map's "get" method. 您可以仅遍历集合,然后调用地图的“ get”方法。

eg 例如

for ( String car : fruit ) {
    Integer value = map.get( car );
    if ( value != null ) {
        System.out.println( value );
    }
}

If the result is not null then print it to the console, otherwise, look for the next one. 如果结果不为null,则将其打印到控制台,否则,寻找下一个。

try this, 尝试这个,

TreeMap<String, Integer> map = new TreeMap<String, Integer>();
    Set<String> fruit = new TreeSet<String>();
    fruit.add("BMW");
    fruit.add("Mercedes");
    fruit.add("Ford");
    fruit.add("Nissan");
    fruit.add("Tesla");

    map.put("BMW", 2);
    map.put("Ford", 2);
    map.put("SomeOther", 2);
    System.out.println(map);

    map.keySet().retainAll(fruit);

    System.out.println(map);
    System.out.println(map.keySet());

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

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