A. Einstein
A. Einstein

Reputation: 45

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.

Although, now I want to only output models that are added to a 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);
    }
  }
}

Upvotes: 0

Views: 89

Answers (2)

AttitudeL
AttitudeL

Reputation: 309

You could just iterate through your set and then invoke the map's "get" method.

e.g.

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.

Upvotes: 1

Saurabh
Saurabh

Reputation: 455

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());

Upvotes: 0

Related Questions