The map
should contain different deep_map
instances, as otherwise every key of map
would have the same Map object, and you have overwritten values.
So you only need as field:
SortedMap<String, Map<String, Integer>> map = new TreeMap<>();
The reading can go as below. I do not use all features, as that would need much explanation.
Path path = Paths.get("file.txt");
try (Stream<String> lines = Files.lines(path, Charset.defaultCharset()) {
lines.map(line -> line.split(" "))
.filter(tokens -> tokens.length == 3)
.forEach(tokens -> {
Map<String, Integer> deepMap = map.get(tokens[0]);
if (deepMap == null) {
deepMap = new HashMap<String, Integer>();
map.put(tokens[0], deepMap);
}
deepMap.put(tokens[1], Integer.parseInt(tokens[2]));
});
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
HOWEVER to have data ordered with descending score:
SortedMap<Integer, Map<String, String>> scoreToCourseToName =
new TreeMap<>(Comparator.reversed());
Path path = Paths.get("file.txt");
try (Stream<String> lines = Files.lines(path, Charset.defaultCharset()) {
lines.map(line -> line.split(" "))
.filter(tokens -> tokens.length == 3)
.forEach(tokens -> {
Integer score = Integer.valueOf(tokens[2]);
Map<String, String> deepMap = scoreToCourseToName.get(score);
if (deepMap == null) {
deepMap = new TreeMap<String, Integer>();
scoreToCourseToName.put(score, deepMap);
}
deepMap.put(tokens[1], Integer.parseInt(tokens[0]));
});
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
And with more feature using:
SortedMap<Integer, Map<String, String>> scoreToCourseToName =
new TreeMap<>(Comparator.reversed());
Path path = Paths.get("file.txt");
try (Stream<String> lines = Files.lines(path, Charset.defaultCharset()) {
lines.map(line -> line.split(" "))
.filter(tokens -> tokens.length == 3)
.forEach(tokens -> {
Integer score = Integer.valueOf(tokens[2]);
Map<String, String> deepMap =
scoreToCourseToName.computeIfAbsent(score, sc -> new TreeMap<>());
deepMap.put(tokens[1], Integer.parseInt(tokens[0]));
});
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}