viperz
@viperz
inspired by Java

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 Петров 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 Петров 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
  • Вопрос задан
  • 150 просмотров
Пригласить эксперта
Ответы на вопрос 1
viperz
@viperz Автор вопроса
inspired by Java
Короче проблема была вот в чем, некоторые текстовые редакторы, такие как стандартный Notepad, иногда могут вставлять символ '\uFEFF' 65279 , который не видим, и например не отображается в Notepad++.
Поэтому по сути и правда, ключа такого не было, поскольку последний ключ был:
'\uFEFF' + "Petrov"
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽