简体   繁体   English

函数式编程/流练习

[英]Functional Programming/Streams Exercise

Write a method named davidist which returns an Optional<Float> result and has 3 parameters:编写一个名为 davidist 的方法,它返回一个Optional<Float>结果并有 3 个参数:

  • a Stream s (Float type) a Stream s(浮点型)
  • a Predicate p for Float type elements浮点型元素的谓词 p
  • 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().方法从流中选择 p 为真的元素并返回:如果有多个元素,则在 p 为真的元素之间应用二元运算符的结果(即 a1 c a2 c a3 c a4 c),否则返回 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.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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