Created
October 4, 2021 08:52
-
-
Save gerritjvv/bbed52f6819ed4312cdfc5941fb1bdcd to your computer and use it in GitHub Desktop.
Averages in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.List; | |
import java.util.LongSummaryStatistics; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
class Averages { | |
public static void main(String[] args) { | |
List<Map<String, Long>> data = List.of( | |
Map.of("age", 18L, "rate", 30L), | |
Map.of("age", 18L, "rate", 15L), | |
Map.of("age", 50L, "rate", 35L) | |
); | |
System.out.println("Summary: " + avgByKey(data)); | |
} | |
public static HashMap<Long, LongSummaryStatistics> avgByKey(List<Map<String, Long>> data) { | |
return data.stream().collect( | |
Collectors.groupingBy( | |
m -> m.getOrDefault("age", 0L), | |
HashMap::new, | |
Collectors.summarizingLong(m -> m.getOrDefault("rate", 0L)) | |
) | |
); | |
} | |
} |
Clojure is runner up for me:
(defn average [data]
(into {} (x/by-key :age :rate x/avg) data))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SQL is much better though:
select age, avg(rate) from person
group by age