function - Java函数链

标签 function java-8

我正在尝试找出以下代码无法编译的原因:

Function<Employee, String> getLastName = (Employee employee) -> {
    return employee.getName().substring(employee.getName().indexOf(" ") + 1);
};

Function<Employee, String> getFirstName = (Employee employee) -> {
    return employee.getName().substring(0, employee.getName().indexOf(" "));
};

Function chained = getFirstName.apply(employees.get(2).andThen(getFirstName.apply(employees.get(2)))); 

不是所有的函数都可以缓存在 java 8 中吗?

最佳答案

确切地说,andThen 应用于该Function 的结果,例如:

Function<Employee, String> chained = getFirstName.andThen(x -> x.toUpperCase());

x -> x.toUpperCase()(或者这可以替换为方法引用 String::toUpperCase)应用于 String 来自 getFirstName 函数的结果。

您如何想象将它们链接在一起?一个 Function 返回 String,因此无法链接。 但是您可以通过单个Function 返回这两个字段:

 Function<Employee, String[]> bothFunction = (Employee employee) -> {
        String[] both = new String[2];
        both[0] = employee.getName().substring(employee.getName().indexOf(" ") + 1);
        both[1] = employee.getName().substring(0, employee.getName().indexOf(" "));
        return both;
    };

关于function - Java函数链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803254/

相关文章:

java - 将 Google App Engine 升级到 Java 8 时出现无法识别的元素 '<runtime>'

从 MongoDB 返回的嵌套文档的 Java 8 Stream 实现

c++ - 函数中的变量初始化

javascript - 避免 jquery 中二分类切换的最佳实践

function - 获取不同内容 map 的所有 map 键[字符串]

java - 在 Tomcat 中运行不同 Java 版本的 Web 应用程序

java - 将 List 中 Objects 的字段设置为相同的值并返回一个列表

C++:错误:预期的主表达式

python - 在运行时向函数对象添加方法

java - Jackson 序列化 可选,YAML 值为空