Skip to content

Instantly share code, notes, and snippets.

@gerritjvv
Created October 4, 2021 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerritjvv/bbed52f6819ed4312cdfc5941fb1bdcd to your computer and use it in GitHub Desktop.
Save gerritjvv/bbed52f6819ed4312cdfc5941fb1bdcd to your computer and use it in GitHub Desktop.
Averages in Java
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))
)
);
}
}
@gerritjvv
Copy link
Author

SQL is much better though:

select age, avg(rate) from person
group by age

@gerritjvv
Copy link
Author

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