[英]Composing Java Bifunction and Function
How can I compose a Bifunction with a function in the folowing example: 在下面的示例中,如何将Bifunction与函数组合在一起:
public static void main(String[] args) {
BiFunction<String, Integer, String> zeroPadding = (string, zeros) -> String.format("%0" +zeros+ "d", Integer.valueOf(string));
Function<String, String> removeNonDigitChars = (string) -> string.replaceAll("\\D", "");
}
First I want to remove non digits chars, and the removeNonDigitChars result pass to zeroPadding BiFunction with parameters. 首先,我想删除非数字字符,并将removeNonDigitChars结果传递给带有参数的zeroPadding BiFunction。
I've tried: 我试过了:
zeroPadding.andThen(removeNonDigitChars).apply("789.65", 8);
and 和
removeNonDigitChars.compose(zeroPadding).apply("789.65", 8);
But none of two works. 但是,两个作品都没有。
Your two attempts are applying the functions in the wrong order. 您的两次尝试均以错误的顺序应用功能。 You want
removeNonDigitChars
applied to the string before giving the string to zeroPadding
. 您希望在将字符串提供给
zeroPadding
之前将removeNonDigitChars
应用于该字符串。
Unfortunately, you can't use andThen()
or compose()
to combined the two functions. 不幸的是,您不能使用
andThen()
或compose()
组合这两个函数。
If you want a combined function, just combine them yourself: 如果需要组合功能,只需自己组合即可:
BiFunction<String, Integer, String> combined = (string, zeros) ->
zeroPadding.apply(removeNonDigitChars.apply(string), zeros);
Then use like this: 然后像这样使用:
combined.apply("789.65", 8) // returns "00078965"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.