如何更改函数<T,R>的参数?



是否可以从Function<T,R>接口吗?

例如,我有类integerMap,它将给定的Function<Integer[],Integer>应用于Integer[]。然而,intWrapper方法接受一个输入类型为int[]的函数。

我的目标是从funwrap方法调用integerMap-并应用其自己的Function的更改版本与相同的指令,只是使用'Integer[]'而不是'int[]',以便将Function<int[],Integer>转换为Function<Integer[],Integer>并在integerMap中使用它。

public static Integer integerMap(Function<Integer[],Integer> integerFun, Integer[] integerArr){
return integerFun.apply(integerArr);
}
Function< Function<int[],Integer> , Function<Integer[],Integer> > funWrap = new Function<Function<int[], Integer>, Function<Integer[], Integer>>() {
@Override
public Function<Integer[], Integer> apply(Function<int[], Integer> integerFunction) {
// Change the input attribute from int[] to Integer[]
}
};

我试图使一个函数integerFunction,它需要两个Function作为属性,但我不明白如何访问输入属性的byte[]以及如何改变它。

让我们看看。您有一个Function<Integer[],Integer>,并希望将其应用到int[]。换句话说:你想要一个Function<int[],Integer>。代码重复是不好的,所以您希望一个方法充当另一个方法的适配器。

Function<Integer[], Integer> fboxed = ints -> Stream.of(ints).reduce(0, Integer::sum); // just a dummy impl
Function<int[], Integer> fprimitive = ints -> fboxed.apply(box(ints));
private static Integer[] box(final int[] ints) {
return IntStream.of(ints).boxed().toArray(Integer[]::new);
// or use https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#toObject(byte[])
}

换句话说:你有两个函数A→R,想要一个函数B→R。这意味着您需要从A转换为B,即A→B。功能:

// A→B
Function<int[], Integer[]> fbox = ints -> IntStream.of(ints).boxed().toArray(Integer[]::new);
// A→R
Function<int[], Integer> fprimitive = ints -> fboxed.apply(box(ints));
// B→R
Function<Integer[], Integer> fboxed = ints -> Stream.of(ints).reduce(0, Integer::sum); // still a dummy impl

当然,Function只是一个SAM类型(单个抽象方法),所以所有东西都可以写成常规方法,并引用这些方法,然后存储在变量中。

class Functions {
public static Integer primitive(final int[] ints) {
return boxed(box(ints));
}
public static Integer boxed(final Integer[] ints) {
return Stream.of(ints).reduce(0, Integer::sum);
}
private static Integer[] box(final int[] ints) {
return IntStream.of(ints).boxed().toArray(Integer[]::new);
}
private static Function<int[], Integer> fint = Functions::primitive;
private static Function<Integer[], Integer> finteger = Functions::boxed;
}

如果上面的内容不够清楚(它可能会令人困惑!),您实际想要做的是让Integer[]->Integer函数展开其参数,然后将其委托给int[]->Integer函数,作为适配器。所以说"转换"实际上是倒置的(Integer[]->int[])

public static Function<Integer[], Integer> funwrap(Function<int[], Integer> intFunction) {
return integers -> intFunction.apply(unbox(integers));
}
private static int[] unbox(final Integer[] ints) {
return Stream.of(ints).mapToInt(x -> x).toArray();
}

所以从外部看,I[]→i[]→II[]→I的转换是难以区分的。

  • 原文件:I[] | I[]→I
  • 改编:I[] | I[]→i[] | i[]->I

相关内容

最新更新