Search code examples
javacollectionsjava-8functional-programmingjava-stream

Functional Programming/Streams Exercise


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

  • a Stream s (Float type)
  • a Predicate p for Float type elements
  • a binary operator for Float type elements

Method chooses from the stream the elements for which p is true and returns: if there are more than one elements, the result of the binary operator applied between the elements for which p is true (i.e a1 c a2 c a3 c a4 c), otherwise it returns Optional.empty().

This is what I've done so far, can somebody help me out?

public Optional<Float> davidist(Stream<Float> s, Predicate<Float> p, byte b) {
    if () {

    } else {
        return Optional.empty();
    }
}

Solution

  • The following method is the one you are looking for:

    public Optional<Float> davidist(
            Stream<Float> stream, Predicate<Float> tester, BinaryOperator<Float> op) {
    
        return stream           // Elements stream
                .filter(tester) // Stream of elements that passed 'tester' test
                .reduce(op);    // Optional<Float> resulting by reducing elements using 'op'
    }
    

    Hope this helps.