user3384231 user3384231 - 12 days ago 5
Java Question

HASHMAP, key present still giving "false" result

Following is my code that returning false even if the key exists:

import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class SequenceNumber {

public static int getSequenceNumber (String TcOrderId){

// Create a hash map to set key values pair.
Map<String, Integer> map = new HashMap<String, Integer>();
int i= 1;

// check if hashmap contains the key.
System.out.println("key present " +map.containsKey(TcOrderId));
if (map.containsKey(TcOrderId))
{
//Key Present
System.out.println("Inside IF ");
int value = map.get(TcOrderId);
System.out.println("value from the key " + value);
map.remove(value);
map.put(TcOrderId, value+1);
return map.get(TcOrderId);
}
else
{
//Key Not present
System.out.println("INSIDE ELSE ");
map.put(TcOrderId, i);
System.out.println("map "+ map);
return map.get(TcOrderId);
}
}

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

String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = getSequenceNumber(sCurrentLine);
System.out.println("seqvalue "+seqvalue);
}

}

}


}

Input data in the file:

1233

1233

1234

The result should be

1

2

1

But everytime its going in the else loop and the result is

1

1

1

I am trying to use HASHMAP as I am creating my own index.

Answer

Something like this should work. Haven't tried running it though.

public class SequenceNumber {

 public static int getSequenceNumber (String TcOrderId, Map<String, Integer> map){  
    if(!map.contains(TcOrderId)){
        map.put(TcOrderId, 0);
    }

    map.put(TcOrderId, map.get(TcOrderId)+1);
    return map.get(TcOrderId);
}

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

    String sCurrentLine;
    BufferedReader br = null;
    Map<String, Integer> map = new HashMap<String, Integer>();
    try {
        br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    {
        while ((sCurrentLine = br.readLine()) != null) {
            //String orderid = sCurrentLine.substring(0, 6);
            System.out.println("reading line " +sCurrentLine);
            int seqvalue = getSequenceNumber(sCurrentLine, map);
            System.out.println("seqvalue "+seqvalue);
        }

    }
Comments