Nir Nir - 21 days ago 6
Java Question

calculate averages of multiple values in java

I have a list which looks like this:

40 4.8980713
5 4.8012613
5 4.8980713
46 4.8980713
5 4.8980713
5 4.8945613
40 4.0120713
5 4.8980713
5 4.8828129
5 4.8000713
40 4.8947213
5 4.8980713
46 4.8980713
5 4.8828125
46 4.8980713


This is a snapshot of a much larger list that contains values of nodes and their arrival times. I need to find the average of arrival time in right column for each node in the left column.

I'm not sure how to approach this in Java using Lists.

Answer

You can first read the CSV file to a List<String>. Then parse it by splitting it on the triple spaces. Then collect it to a Map<Integer, Double> where the keys are your nodes and the values are the average. You can use the averagingDouble from Collectors.

Code then looks like this:

List<String> lines = Files.readAllLines(Paths.get("/path/to/arrivals.csv"));

Map<Integer, Double> averages = lines.stream()
                                     .map(s -> s.split("   "))
                                     .collect(
                                        Collectors.groupingBy(
                                           r -> Integer.parseInt(r[0]),
                                           Collectors.averagingDouble(v -> Double.parseDouble(v[1]))
                                        )
                                     );

If you run this for your example you get:

{5=4.872644944444445, 40=4.6016213, 46=4.8980713}