简体   繁体   中英

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 (ie 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();
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM