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: