I would like to create a simple class applying common statistics using lambda expression. I am wondering how can I avoid using the switch case in the statistic() method?
For example, I may want to write a new lambda to calculate the variance of the list, etc.
Thank you.
public class DescriptiveStatistics {
public static void main(String[] args) {
List<Double> numbers = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
numbers.stream().forEach(n-> System.out.print(n + " "));
System.out.println();
System.out.println("Descriptive statistics");
System.out.println("Sum: " + statistic(numbers, "Sum"));
System.out.println("Max: " + statistic(numbers, "Max"));
System.out.println("Min: " + statistic(numbers, "Min"));
System.out.println("Average: " + statistic(numbers, "Average"));
System.out.println("Count: " + statistic(numbers, "Count"));
}
private static double statistic(List<Double> numbers, String function) {
switch (function.toLowerCase()) {
case "sum":
return numbers.stream().mapToDouble(Double::doubleValue).sum();
case "max":
return numbers.stream().mapToDouble(Double::doubleValue).max().getAsDouble();
case "min":
return numbers.stream().mapToDouble(Double::doubleValue).min().getAsDouble();
case "average":
return numbers.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
case "count":
return numbers.stream().mapToDouble(Double::doubleValue).count();
}
return 0;
}
I have in mind of a method like this
private static double newStatistics(List<Double> numbers, Function<Double, Double> function){
return numbers.stream().mapToDouble(Double::doubleValue).function();
}
enum
(if you know ahead of time all the functions) or a Strategy interface (if you need to be able to plug new ones in at runtime).