Andrey Meshcheryakov Andrey Meshcheryakov - 6 months ago 52
Java Question

HashMap and containsKey() method

I need to read some data from file and sort it. But when I try to use

method, It doesn't work and I have 2 different keys with the same filling. May be, the reason why I have a problem is that the method has Object parameter type and there are links to objects compare. But how can I compare String keys in HashMap?

public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
Map<String, Double> map = new HashMap<>();
while (reader.ready()) {
String[] ss = reader.readLine().split(" ");
String key = ss[0];
String val = ss[1];
double value = Double.parseDouble(val);
if (map.containsKey(key)) {
map.put(key, map.get(key) + value);
else map.put(key, value);

for (Map.Entry<String, Double> pair : map.entrySet())
System.out.println(pair.getKey() + " " + pair.getValue());


This is what the above program outputs:

Sidorov 4.0
Petrov 3.0
Ivanov 5.0
Ivanov 33.0

hzhang@ubuntu:~$ cat sample.csv 
hello 4.0
hi 3.1
hello 5.0
hzhang@ubuntu:~$ java Solution sample.csv 
hi 3.1
hello 9.0

I have tested your code on my side(Ubuntu server), and it gave me the expected result.

If your key is an instance of Class A other than String, you have to override hashCode() and equals() method for class A.

HashMap stores all elements in buckets based on the objects' keys, it stores element in specific bucket based on the object's hash code value. For example, if two objects a1 and a2 have the same hash code value, they would be put into the same bucket's list, and when you retrieve a1, firstly it checks the hash code and find the correct bucket, and then iterate the elements list and compares the equality of the object using equals