functional programming - Function Composition

本文探讨了函数组合在Java 8中的应用,通过具体示例展示了如何使用函数接口创建新的函数,包括compose和andThen方法的使用。文章还介绍了String类的substring方法和join方法,展示了它们在字符串操作中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Function composition basically means "pasting functions together to create new functions," and it's commonly considered a part of functional programming.

For example:

// functional/FunctionComposition.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.function.*;

public class FunctionComposition {
  static Function<String, String>
      f1 =
          s -> {
            System.out.println(s);
            return s.replace('A', '_');
          },
      f2 = s -> s.substring(3),
      f3 = s -> s.toLowerCase(),
      f4 = f1.compose(f2).andThen(f3);

  public static void main(String[] args) {
    System.out.println(f4.apply("GO AFTER ALL AMBULANCES"));
  }
}
/* Output:
AFTER ALL AMBULANCES
_fter _ll _mbul_nces
*/
public String substring(int beginIndex)

Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Examples:

 "unhappy".substring(2) returns "happy"

 

public static String join(CharSequence delimiter,
                          CharSequence... elements) // this method since 1.8

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

For example,

     String message = String.join("-", "Java", "is", "cool");
     // message returned is: "Java-is-cool"
 

Note that if an element is null, then "null" is added.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/functional/FunctionComposition.java

3. https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值