P
P
Pavel Dudenkov2015-12-30 20:37:12
Java
Pavel Dudenkov, 2015-12-30 20:37:12

TreeMap null for get(String key)?

Hi guys,
My goal was to read from file, which formatted as [name] [value] and put into console output in ascending order for names + if there are the same names values ​​should be summed up. To avoid ordering I decided to use TreeMap, but for file:

Петров 2
Сидоров 6
Иванов 1.35
Петров 3.1

code below retuns null value for Petrov key on line where value is 3.1 . Then I thought that there is some unobvious way to compare Strings in TreeMap, so I tried to pass Comparator, but the same, for line Petrov 3.1 it returns null on Double currentValue = deals.get(name);
Could you help me to understand what's the problem here?
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class Solution {
    public static void main(String[] args) throws Exception {
        //String fname = args[0];
        String fname = "prices.txt";

        TreeMap<String, Double> deals = new TreeMap<String, Double>();
        BufferedReader buffer = new BufferedReader(new FileReader(fname));
        String currentLine = null;
        while ((currentLine = buffer.readLine()) != null) {
            String name = currentLine.split(" ")[0];
            double value = Double.parseDouble(currentLine.split(" ")[1]);
            Double currentValue = deals.get(name);
            if (currentValue == null) {
                deals.put(name, value);
            } else {
                deals.put(name, value+currentValue);
            }
        }
        buffer.close();

        for (Map.Entry entry : deals.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

Screenshot from debugger:
e0f7da30a02440ebaeef11485d7f6f71.JPG

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Dudenkov, 2015-12-31
@viperz

In short, the problem was that some text editors, such as standard Notepad, can sometimes insert the character '\uFEFF' 65279 , which is not visible, and for example is not displayed in Notepad++.
Therefore, in fact, there was no such key, since the last key was:
'\uFEFF' + "Petrov"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question