Functional Prog./Streams Ex

Write a method davidist that returns an Optional<Float> result and has 3 parameters:

  • A Stream<Float> named s
  • A Predicate<Float> for Float elements named p
  • A binary operator for Float elements named b

The method chooses from the stream the elements for which p is true and returns the result of the binary operator applied between the elements for which p is true if there are more than one elements, otherwise it returns Optional.empty().

public static Optional<Float> davidist(Stream<Float> s, Predicate<Float> p, BinaryOperator<Float> b) {
    List<Float> filtered = s.filter(p).collect(Collectors.toList());
    if (filtered.size() > 1) {
        Float result = filtered.get(0);
        for (int i = 1; i < filtered.size(); i++) {
            result = b.apply(result, filtered.get(i));
        return Optional.of(result);
    } else {
        return Optional.empty();