【问题标题】:Functional version of operators in Java?Java中运算符的功能版本?
【发布时间】:2016-09-01 18:04:58
【问题描述】:

我正在寻找一个等效于 python 的 Operator python 包。这将允许在 reduce 中使用运算符作为函数(例如),而无需创建新的 lambda 函数

【问题讨论】:

  • Integer::sum,但我认为其余的都没有预先打包。
  • java与python相去甚远...如果您发布您想要实现的目标以及到目前为止您尝试过的内容会更好...
  • 我只想尽可能用 Stream.reduce(Operators::or) 替换 Stream.reduce((x, y) -> x || y) ,因为它看起来更干净并且避免定义新的 lambda
  • @Phrodo_00 您正在寻找Boolean::logicalOr。但坦率地说,它实际上不太可能比(x, y) -> x || y 更有效。
  • 我喜欢Boolean::logicalOr。对我来说,它似乎更具可读性。并且该方法肯定是在考虑到这样的应用程序的情况下引入的(对于 99.99 % 的使用,效率不应成为选择的驱动因素)。

标签: java java-8


【解决方案1】:

如果您愿意尝试 Scala,可以将一些 Java 代码引入 Scala 应用程序。然后你可以做你要求的事情:

// Simulate a small stream
val stream = true #:: false #:: true #:: Stream.empty

// With lambda
val result1 = stream.reduce(_ || _)
println("Result 1 = " + result1)

// Define function 
val OpOR = (x: Boolean, y: Boolean) => {x || y}

// Pass function as argument to perform OR operation
val result2 = stream.reduce(OpOR)
println("Result 2 = " + result2)

在这两种情况下,每个结果的输出都是true

见:

http://alvinalexander.com/scala/how-to-walk-scala-collections-reduceleft-foldright-cookbook

http://alvinalexander.com/scala/how-to-use-stream-class-lazy-list-scala-cookbook

【讨论】:

    【解决方案2】:

    在 Java 8 中,使用来自 cmets 的信息:

    import java.util.Optional;
    import java.util.stream.*;
    import static java.lang.Boolean.FALSE;
    import static java.lang.Boolean.TRUE;
    
    public class Main {
        void reduceDemo() {
            Stream<Boolean> booleanStream = Stream.of(TRUE, FALSE, TRUE);
    
            Optional<Boolean> reduced = booleanStream.reduce(Boolean::logicalOr);
    
            System.out.println("reduced:  " + reduced.get());
        }
    
        public static void main(String[] args) {
            Main m = new Main();
            m.reduceDemo();
        }
    }
    

    输出:

    reduced:  true
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多