I have a text file with a file that on each line contains a pair of names and an amount similar to this:
Mike 5
Kate 2
Mike 3
I need to sum these values using a key. I solved it this way
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
try {
Files.lines(Paths.get("/Users/walter/Desktop/stuff.txt"))
.map(line -> line.split("\\s+")).forEach(line -> {
String key = line[0];
if (map.containsKey(key)) {
Integer oldValue = map.get(key);
map.put(key, oldValue + Integer.parseInt(line[1]));
} else {
map.put(line[0], Integer.parseInt(line[1]));
}
});
map.forEach((k,v) -> System.out.println(k + " " +v));
} catch (IOException e) {
e.printStackTrace();
}
;
}
How could I improve this code in a more functional way, with the ability to process data simultaneously (using parallel threads, etc.).
source
share