user2490712
user2490712

Reputation: 135

Java HashMap returning null values even when key is present

I am working on a project in which we insert key and value pairs in a Map.

If the key is present in the Map, my code returns the value for that key.

However, the HashMap is not returning the expected values, even though the key is present.

First I read the key and value pairs from a file, then I read another file which has almost the same keys as the first file.

Then I return values for some keys, but for many of them the value is null.

Here is a snippet of my code:

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

LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

while (scanner.hasNextLine())
{
   String[] columns = scanner.nextLine().split(";");
   map.put(columns[0], columns[1]);
}

System.out.println(map);

for (Map.Entry<String, String> entry : map.entrySet())
{ // name is the input of second file
    if (entry.getKey().equals(name)) 
    {
        num = entry.getValue();         
        fun(num);
    }
}

My input file is

abc;1

def;2

ghi;3

... and name will be abc

def

Upvotes: 3

Views: 11163

Answers (2)

Charlie
Charlie

Reputation: 9108

This issue can come up if the hashCode of the object changes after insertion.

If you're modifying an object that's used as a key in a hashMap, you have two options:

  1. Replace the HashMap with an IdentityHashMap. This may have unintended consequences as two objects with the same hashCode will no longer be considered equivalent when putting/getting from the map, including exact clones.
  2. Before updating the key in such a way the hashCode is changed, remove it from the map, update the key, then re-insert into the map.

Upvotes: 3

anubhava
anubhava

Reputation: 785156

Strings that are being compared might have white space, linefeed, newline characters.

As we suspected earlier your input file train.txt has man trailing white-spaces and that is causing map lookup to fail. Besides that your Java code had many redundant block of code. I have cleaned it up. Here is your modified code:

import java.io.*;
import java.util.*;
public class ExampleClass1 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(new FileReader("trainnames.txt"));
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        while (scanner.hasNextLine()) {
            String[] columns = scanner.nextLine().split(";");
            map.put(columns[0].trim(), columns[1].trim());
        }
        scanner.close();
        System.out.println("******** map is: " + map);
        File file = new File("onn.csv"); // output file
        FileWriter fileWriter = new FileWriter(file);
        scanner = new Scanner(new FileReader("train.txt"));
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (line.charAt(0) == '>') {
                //System.out.println("==== line: [" + line + ']');      
                String num = map.get(line);
                no(num, fileWriter);
            }
        }
        scanner.close();
        fileWriter.close();
    }

    public static void no(String num, FileWriter fileWriter) throws IOException {
        fileWriter.append(num + ',' + System.getProperty("line.separator"));
        System.out.println(num);                                        
    }
}

Upvotes: 4

Related Questions