gpt4 book ai didi

java - 创建一个方法,该方法接受可能具有不同类型的可变长度的 Function 参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:49:59 24 4
gpt4 key购买 nike

假设我有一个字符串:String s = "1,2,3,4,5,6" .我想创建一个方法 combineFunctions()这将采用 Function 的可变长度序列s 作为参数并按该顺序应用所有操作。

函数可能有不同<T,U>类型。

此类函数的示例用法如下:

Combine<String> c = new Combine<>(s);
List<String> numbers = c.combineFunctions(splitByComma);
Integer max = c.combineFunctions(splitByComma,convertToInt, findMax);

我试过的(<U>在这里用处不大):

public <U> void combineFunctions(
Function<? extends Object, ? extends Object>... functions) {

}

但我一直在获取 Function 的最后一个类型秒。我也在考虑递归方法,但 varargs 参数必须是最后一个。

是否可以用 Java 实现这样的方法?

最佳答案

这样一个函数的问题是你失去了所有编译时类型检查和转换是必要的。

这将是一个实现,使用 andThen 将函数组合在一起。这看起来很难看,因为所有的类型转换,我不确定你能做得更合适。另请注意,这需要创建 2 个 Stream 管道,而实际上只需要 1 个。

public static void main(String[] args) throws Exception {
String str = "1,2,3,4,5,6";
Function<Object, Object> splitByComma = s -> ((String) s).split(",");
Function<Object, Object> convertToInt = tokens -> Stream.of((String[]) tokens).map(Integer::valueOf).toArray(Integer[]::new);
Function<Object, Object> findMax = ints -> Stream.of((Integer[]) ints).max(Integer::compare).get();
Integer max = (Integer) combineFunctions(splitByComma, convertToInt, findMax).apply(str);
System.out.println(max);
}

@SafeVarargs
private static Function<Object, Object> combineFunctions(Function<Object, Object>... functions) {
return Arrays.stream(functions)
.reduce(Function::andThen)
.orElseThrow(() -> new IllegalArgumentException("No functions to combine"));
}

要匹配您问题中的代码,您可以将其包装到这样的类中:

public class Combiner<R> {

private Object input;

public Combiner(Object input) {
this.input = input;
}

@SuppressWarnings("unchecked")
@SafeVarargs
public final R combineFunctions(Function<Object, Object>... functions) {
return (R) Arrays.stream(functions)
.reduce(Function::andThen)
.orElseThrow(() -> new IllegalArgumentException("No functions to combine"))
.apply(input);
}

}

关于java - 创建一个方法,该方法接受可能具有不同类型的可变长度的 Function 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33259637/

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