Search code examples
javahashmapbufferedreader

Making a HashMap from a text file using Buffered Reader?


I am having trouble coding a method that given an argument, a file name, reads through the file which will contain words and makes a Hashmap with the key as the first letter e.g. for a word in the file such as apple , 'a' is the key and value is 'apple'.

Code I have currently:

public class WordStore {
HashMap<String, List<String>> map;
File filename;

public WordStore() {
     map = new HashMap<String, List<String>>();
}

public WordStore(File file) throws IOException {
    map = new HashMap<String, List<String>>();
    BufferedReader br = null;
    //k = "/Users/hon/eclipse-workspace/Assignment4/src/wordbank.txt"
    try{
        File filename = new File(k);
        FileReader fr = new FileReader(filename);
        br = new BufferedReader(fr);    
        while(br.readLine()!=" ") {
        String word ="";
        word = br.readLine();
        String key = ""+(word.charAt(0));
        map.put(key, word);
        }

    }
    catch(IOException e) {
        System.out.println("File not found exception caught!");
    }
    finally {
        if(br != null) {
            try {
                br.close();
            }
        catch(IOException e) {
            e.printStackTrace();
        }
        }
    }

}
public void put(String key, String word) {
    if(map.containsKey(key)) {
        (map.get(key)).add(word);
    }
    else {
    List<String> names = new ArrayList<>();
    names.add(word);
    map.put(key, names);
    }
}
}

I have an error in the constructor WordStore(File file), at map.put(key, word) which says the method put(String, List<String>) in the type HashMap<String, List<String>> is not applicable for the argument (String, String).

I tried renaming my put method so that it uses my method and not the hashmap put method but that doesn't work either.


Solution

  • You are attempting to place a String value where a List is expected. This is because you've called map's normal put method. Call your own put method instead, which handles the lists already.

    put(key, word);
    

    Also, the way you're reading from the file isn't right. First, you're comparing strings with != which isn't correct. Then, you're calling readLine twice per loop. The top of the loop should be:

    String word;
    while( (word = br.readLine() ) != null) {
    

    This reads a line and compares it to null in the same line to test for end-of-file.