The sum of the values ​​on the map for a particular key

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) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ;

}

How could I improve this code in a more functional way, with the ability to process data simultaneously (using parallel threads, etc.).

+4
source share
1 answer

If you want to write functional code, this rule is: do not use forEach. This is an imperative decision and violates the functional code.

(), ():

Map<String, Integer> map = 
    Files.lines(Paths.get("/Users/walter/Desktop/stuff.txt"))
         .map(s -> s.split("\\s+"))
         .collect(groupingBy(a -> a[0], summingInt(a -> Integer.parseInt(a[1]))));

. Stream, Collectors.groupingBy(classifier, downstream), :


( ), forEach, Map.merge(key, value, remappingFunction), :

map.merge(line[0], Integer.valueOf(line[1]), Integer::sum);

line[0] Integer.valueOf(line[1]), , ( ).

+9

Source: https://habr.com/ru/post/1615041/


All Articles