Answer the question
In order to leave comments, you need to log in
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
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());
}
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question