java - 映射与函数接口关联的管道运算符
问题描述
我不明白为什么String::toUpperCase()
表达式在 Stream map
pipeline中工作正常。当我在这里看这个例子时:
Stream.of("test1", "test2", "test3", "test4")
.filter(s -> s.contains("r"))
.map(s -> s + "map")
.map(String::toUpperCase)
.forEach(System.out::println);
当我查看下面示例中使用的映射运算符的定义时,map(Function<? super String, ? extends String> mapper)
我看到使用了函数设计模式。
在这个例子.map(s -> s + "map")
中很好,据我了解,我们正在寻找更精确的 Function R apply(T t);
,这完全是 lambda 表达式s -> s + "map"
在这里所说的我们有一个带有参数 s 的函数,它返回 s + String "map" 并且它符合这个规范. T
并且R
,它们存在。
另一方面第二个map(String::toUpperCase)
,我不明白为什么表达式toUpperCase
被认为是一个Function
接口,我应该注意这个函数的核心是这样的
public String toUpperCase() {
return toUpperCase(Locale.getDefault());
}
我们正在寻找R apply(T t);
这种方法中没有 T 参数toUpperCase
?为什么这个有效?
解决方案
apply
就接口的方法而言,更容易理解的Function
是方法引用的匿名类表示String::toUpperCase
。它是这样的——
new Function<String, String>() {
@Override
public String apply(String str) { // read as given a String return a String (uppercased)
return str.toUpperCase();
}
}
str
提供给上述apply
方法的字符串 arguments( ) 是来自Stream
上一个操作之后的那些map
。
推荐阅读
- bash - 使用管道查看器显示已处理文件列表的解压缩进度
- elixir - 如何在 Elixir 中对 nil 或空白字符串进行模式匹配?
- java - 如何获取请求和响应信息并将它们作为发布请求发送到 Jersey?
- javascript - 如何更改 Anychart 点图的颜色。?
- r - 在 R 中指定错误消息的调用函数
- opendaylight - 我们应该使用 READ 交易吗?
- angular - 错误单击过滤器导致的行
- java - 将变量传递给有意图的两个活动
- oracle - oracle sql如何获取星期几
- mysql - 使用 mysql 创建新项目时找不到“config/databases/mysql.yml”