我正在探索scala和Java 1.8,但无法在Java 1.8 Lambda表达式中找到等效的代码。

Scala代码:

object Ex1 extends App {

  def single(x:Int):Int =x
  def square(x:Int):Int = x * x
  def cube(x:Int):Int = x*x*x

  def sum(f:Int=>Int,a:Int,b:Int):Int=if (a>b) 0 else f(a) + sum(f,a+1,b)

  def sumOfIntegers(a:Int,b:Int)=sum(single,a,b)
  def sumOfSquares(a:Int,b:Int)=sum(square,a,b);
  def sumOfCubes(a:Int,b:Int)=sum(cube,a,b);

  println(sumOfIntegers(1,4));
  println(sumOfSquares(1,4));
  println(sumOfCubes(1,4));

}

output:

10
30
100




Java的

public class Test1{
    public int single(int x){
        return x;
    }
    public int square(int x){
        return x * x;
    }
    public int cube(int x){
        return x * x * x;
    }
    // what's next? How to implement sum() method as shown in Scala?
    // Stuck in definition of this method, Stirng s should be function type.
    public int sum( Sring s , int a, int b){
        // what will go here?
    }
    public int sumOfIntegers(int a, int b){
        return sum("single<Function> how to pass?",a,b);
    }
    public int sumOfSquares(int a, int b){
        return sum("square<Function> how to pass?",a,b);
    }
    public int sumOfCubes(int a, int b){
        return sum("cube<Function> how to pass?",a.b);
    }
}


使用JDK 1.8是否可以实现相同的目的?

最佳答案

您将需要定义将要使用的方法。 Java随附的唯一一个是Function<X,Y>,它(与Integer一起使用)可用于singlesquarecube,而BiFunction<T,Y, R>可以用于三个sumOf

interface Sum {
    Integer apply(Function<Integer, Integer> func, int start, int end);
}


单个,正方形和多维数据集可以是类中的方法(请参见cube或内联(请参见其他两个)。它们是Fuction s。然后可以将此函数传递给其他方法,并使用variableName.apply进行调用。

  class Test
{
    private static Integer sum(Function<Integer, Integer> func, int a, int b) {
        if (a>b)
            return 0;
        else return func.apply(a) + sum(func,a+1,b);
    }

    private static Integer cube(Integer a) {
        return a * a * a;
    }

    public static void main (String[] args) throws java.lang.Exception
    {

        Function<Integer,Integer> single = a -> a;
        Function<Integer,Integer> square = a -> a * a;
        Function<Integer,Integer> cube = Test::cube;

        // You can not do the sum in-line without pain due to its recursive nature.
        Sum sum = Test::sum;

        BiFunction<Integer, Integer, Integer> sumOfIntegers = (a, b) -> sum.apply(single, a, b);
        BiFunction<Integer, Integer, Integer> sumOfSquares = (a, b) -> sum(square, a, b); // You could just use the static method directly.
        BiFunction<Integer, Integer, Integer> sumOfCubes = (a, b) -> sum(cube, a, b);

        System.out.println(sumOfIntegers.apply(1,4));
        System.out.println(sumOfSquares.apply(1,4));
        System.out.println(sumOfCubes.apply(1,4));
    }


}

10-06 14:01
查看更多