Skip to content

Instantly share code, notes, and snippets.

@cowlike
Created November 4, 2017 17:11
Show Gist options
  • Save cowlike/de57ab95fc9f95d9d6be505a39fd53e1 to your computer and use it in GitHub Desktop.
Save cowlike/de57ab95fc9f95d9d6be505a39fd53e1 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Main {
static OptionalDouble toDouble(String s) {
OptionalDouble val = OptionalDouble.empty();
try {
val = OptionalDouble.of(Double.parseDouble(s));
}
catch (NumberFormatException e) {
//leave empty
}
return val;
}
public static void main(String[] args) {
double score =
Arrays.asList("1","2","foo","4").stream()
.map(Main::toDouble)
.filter(OptionalDouble::isPresent)
.mapToDouble(OptionalDouble::getAsDouble)
.average().orElse(0.0);
System.out.println(score);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment