user655321
user655321

Reputation: 143

Parsing a CSV file into HashMap stores a null value

I am trying to read off a csv file and store the data into a hash map. I am able to correctly add the key but when adding the value, it is adding null for every single one. I am not sure why. Here is my code:

EDITED CODE:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class ExampleActivity {
    public static HashMap<String, String> hm = new HashMap<String, String>();

    public static void readCountry() throws IOException{
        BufferedReader reader = new BufferedReader(new FileReader("countries.csv"));    
        String line;
        HashMap<String, String> hm = new HashMap<String, String>();

        while ((line = reader.readLine()) != null) {
            String str[] = line.split(",");
            if (str.length > 1) {
                System.out.println("Data 0: " + str[0]);
                System.out.println("Data 1: " + str[1]);
                hm.put(str[0].trim(), str[1]);
            }

        }
        //System.out.println(hm);
    }

    public static void main(String[] args) throws IOException {

        readCountry();

        Scanner in = new Scanner(System.in);
        String l = null;

        System.out.println("Please enter a three letter country:");
        l = in.nextLine();
        l = l.trim();
        // System.out.println("Country Code: " + l + "\nCountry Name: " +
        // hm.get(l) );
        if (hm.containsKey(l)) {
            System.out.println("Country Code: " + l + "\nCountry Name: "
                + hm.get(l));
        } else {
            System.out.println("Missing key for " + l);
        }
    }
}

Here is a sample of the CSV file

AFG,Afghanistan
AGO,Angola
AIA,Anguilla
...

Here is a screenshot of the output: enter image description here

Upvotes: 0

Views: 408

Answers (3)

SubOptimal
SubOptimal

Reputation: 22963

Using the Stream API you could start with following snippet.

Path path = Paths.get("countries.txt");
Map<String, String> countries = Files.lines(path, StandardCharsets.UTF_8)
        .filter((String l) -> !l.isEmpty())
        .map((Object t) -> ((String) t).split(",", 2))
        .collect(toMap((String[] l) -> l[0], 
                (String[] l) -> l.length > 1 ? l[1] : ""));
System.out.println("countries = " + countries);

output

countries = {AFG=Afghanistan, AIA=Anguilla, AGO=Angola}

The snippet filter out empty lines and for lines without a , the value is assigned as an empty string.

edit Your amended readCountry would look like

public static void readCountry() throws IOException {
    Path path = Paths.get("countries.txt");
    Map<String, String> hm = Files.lines(path, StandardCharsets.UTF_8)
            .filter((String l) -> !l.isEmpty() && l.contains(","))
            .map((Object t) -> ((String) t).split(",", 2))
            .peek((String[] l) -> 
                 System.out.printf("Data 0: %s%nData 1: %s%n", l[0], l[1]))
            .collect(toMap((String[] l) -> l[0],
                    (String[] l) -> l[1]));
}

it store the key-value pairs in hm and produce as output

Data 0: AFG
Data 1: Afghanistan
Data 0: AGO
Data 1: Angola
Data 0: AIA
Data 1: Anguilla

Upvotes: 0

Draken
Draken

Reputation: 3189

Try this:

while((line = reader.readLine()) != null){
    String str[] = line.split(",");
    if (str.size() > 1){
        System.out.println("Data 0: " + str[0]);
        System.out.println("Data 1: " + str[1]);
        hm.put(str[0], str[1]);
    }
}

Your for loop is unecessary

Also look at Dark Knight's answer for your null values issue

EDIT

Can you add this to your code and see what it does:

if (hm.containsKey(l)
    System.out.println("Country Code: " + l + "\nCountry Name: " + hm.get(l) );
else
    System.out.println("Missing key for " + l);
System.out.println("Printing hashmap");
for(Entry<String, String> entry : hm.entrySet()) {
{
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());   
}

EDIT2

hm.put(str[0].trim(), str[1]);

And the next bit

Scanner in = new Scanner(System.in);
String l;
System.out.println("Please enter a three letter country:");
l = in.nextLine();
l = l.trim();

Upvotes: 1

Dark Knight
Dark Knight

Reputation: 8347

Comment out method local declaration of hashmap and it should work fine. Make change to code as below:

public static void readCountry() throws IOException{

    BufferedReader reader = new BufferedReader(new FileReader("d:/countries1.csv")); 
    String line;
  //  HashMap<String, String> hm = new HashMap<String, String>(); Remove this line

Upvotes: 3

Related Questions