英文:
Stream of Function[]
问题
class A {
static void run() {
Integer a = applyConversions(3, x -> x * 3, x -> x + 4); // output: 13
String b = applyConversions("One", s -> "Two " + s, String::toUpperCase); // output: OneTwo
}
static <T> T applyConversions(T value, Function<T, T>... conversions) {
/*
todo: apply each conversion function to 'value'
==>My Ugly solution<==
final Object[] valueHelper = {null};
valueHelper[0] = value;
Stream.of(conversions).forEach(s -> valueHelper[0] = s.apply((T)valueHelper[0]));
return (T)valueHelper[0];
*/
return value;
}
}
英文:
how can i use Stream for Function[]? My solution looks very ugly plus i know that this can be done by using reduce().
class A {
static void run() {
Integer a = applyConversions(3, x -> x * 3, x -> x + 4); // output: 13
String b = applyConversions("One", s -> "Two " + s, String::toUpperCase); // output: OneTwo
}
static <T> T applyConversions(T value, Function<T, T>... conversions) {
/*
todo: apply each conversion function to 'value'
==>My Ugly solution<==
final Object[] valueHelper = {null};
valueHelper[0] = value;
Stream.of(conversions).forEach(s-> valueHelper[0] = s.apply((T)valueHelper[0]));
return (T)valueHelper[0];
*/
return value;
}
}
I can change only signature and body of 'applyConversions' method
答案1
得分: 2
你似乎想要使用 andThen
来简化函数。假设 conversions
不能是空的,你可以这样做:
static <T> T applyConversions(T value, Function<T, T>... conversions) {
return Arrays.stream(conversions).reduce(Function::andThen).get().apply(value);
}
如果它可以是空的,你需要决定在它为空时要返回什么值。
return Arrays.stream(conversions).reduce(Function::andThen)
.map(x -> x.apply(value)).orElse(someDefaultValue);
如果你希望它使用 value
作为默认值,你可以使用 orElse(Function.identity())
替代 get
来获取可选值。
return Arrays.stream(conversions)
.reduce(Function::andThen).orElse(Function.identity())
.apply(value);
}
英文:
You seem to want to reduce
the functions using andThen
. Assuming conversions
can't be empty, you can do:
static <T> T applyConversions(T value, Function<T, T>... conversions) {
return Arrays.stream(conversions).reduce(Function::andThen).get().apply(value);
}
If it can be empty, you need to decide what to return when it is empty.
return Arrays.stream(conversions).reduce(Function::andThen)
.map(x -> x.apply(value)).orElse(someDefaultValue);
If you want it to use value
as the default value, you do orElse(Function.identity())
instead of get
ting the optional.
return Arrays.stream(conversions)
.reduce(Function::andThen).orElse(Function.identity())
.apply(value);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论