3

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

6
  • Can you show how your text file look like? Commented Aug 1, 2013 at 15:22
  • 1
    Why the for loop, when map.get(name) would do the job? Commented Aug 1, 2013 at 15:24
  • 3
    I suspect there might be some trailing or leading whitespaces. Commented Aug 1, 2013 at 15:27
  • by using map.get(name) also it is returning null values Commented Aug 1, 2013 at 17:06
  • Please include System.out.printf("@%s@\n", name) outside the loop and System.out.printf("@%s@\n", entry.getKey()) inside the loop and update the question with the output? The @s are to show whitespaces Commented Aug 1, 2013 at 17:13

2 Answers 2

4

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);                                        
    }
}
Sign up to request clarification or add additional context in comments.

14 Comments

\W contains many more characters than just whitespace. And replaceAll will remove all of them, not just those at the ends.
You can use name.trim() to remove trailing and leading whitespaces.
Yes you can definitely do that to remove white-spaces only from both ends.
Show output of System.out.println(map); and System.out.println('[' + name + ']');
output of map:{1NBG=1, 1MBD=1, 1MBM=1, 1LN1=1, 1BMBM=1, 1MLLM=1, 1DMN=2, 1CYZ=2, 5CYTR=2, 1CC5 =2, 351C=2, 1GKS=2, 1MOFM1=2, 1ETPM1=2, 1ETPM2=2, 1YRNM=3, 1YRNB=3, 1OCTC1=3, 1F JLM=3, 1RES=3, 1PDNC=3, 1ZGNM1=3, 1ZGNM2=3, 1SFE_1=3, 1BZM_1=3, 1LEM=3, 1MOY=3, 1CGPM1=3, 1OPC=3, 1ETD=3, 1PUEE=3, 2NTS=3, 1DPRM1=3, 1XGSM1=3, 1FOW=3, 2LZGM=4, 1BBNM=4, 1CGO=4, 1CPQ=4, 2NMQM=4, 1MTMP=4, 1BUCM1=4, 1FMPB=4, 1BGC=5, 1CNT1=5}
|
3

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.

2 Comments

How do you handle this though?
@Dylan I've added some alternatives

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.