[英]Composing Java Bifunction and Function
在下面的示例中,如何将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", "");
}
首先,我想删除非数字字符,并将removeNonDigitChars结果传递给带有参数的zeroPadding BiFunction。
我试过了:
zeroPadding.andThen(removeNonDigitChars).apply("789.65", 8);
和
removeNonDigitChars.compose(zeroPadding).apply("789.65", 8);
但是,两个作品都没有。
您的两次尝试均以错误的顺序应用功能。 您希望在将字符串提供给zeroPadding
之前将removeNonDigitChars
应用于该字符串。
不幸的是,您不能使用andThen()
或compose()
组合这两个函数。
如果需要组合功能,只需自己组合即可:
BiFunction<String, Integer, String> combined = (string, zeros) ->
zeroPadding.apply(removeNonDigitChars.apply(string), zeros);
然后像这样使用:
combined.apply("789.65", 8) // returns "00078965"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.