gpt4 book ai didi

java - Scala -> Java,将函数作为参数传递给另一个函数

转载 作者:行者123 更新时间:2023-11-29 03:02:53 24 4
gpt4 key购买 nike

我正在探索 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));
}


}

关于java - Scala -> Java,将函数作为参数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33740010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com