user3402248
user3402248

Reputation: 469

Reading a text file to a HashMap in Java

I have a text file in the following format:

Student1 Marks
Student2 Marks

The first column is the key.

This is what I have tried so far

Scanner scanner = new Scanner(new FileReader("marks.txt"));

    HashMap<String,Integer> map = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split("\t");

        map.put(columns[0],columns[1]);
    }

    System.out.println(map);        


}

Upvotes: 0

Views: 9551

Answers (2)

Tanix
Tanix

Reputation: 106

(With a little help from the comments) your code should be reading into the HashMap already, so i assume your problem is printing the HashMap after reading it in.

System.out.println(map) only gives you the representation of the map object. I suggest reading this: Convert HashMap.toString() back to HashMap in Java

To print all elements of that HasMap you could iterate over it, like shown here: Iterate through a HashMap

Upvotes: 0

Vasco Lameiras
Vasco Lameiras

Reputation: 364

Just make sure you parse the marks and that the values are indeed tab separated, otherwise code worked for me right away

    Scanner scanner = new Scanner(new FileReader("marks.txt"));

    HashMap<String,Integer> map = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split("\t");

        map.put(columns[0],Integer.parseInt(columns[1]));
    }

    System.out.println(map);        

Upvotes: 1

Related Questions