首页 > 解决方案 > 映射与函数接口关联的管道运算符

问题描述

我不明白为什么String::toUpperCase()表达式在 Stream mappipeline中工作正常。当我在这里看这个例子时:

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?为什么这个有效?

标签: javajava-8functional-programmingjava-streammapping

解决方案


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


推荐阅读