jdk8函数式编程

java8函数式编程的写法

直接上代码:
先定义一个接口:

public interface MyInterface {
    Object handler(String s);
}

那么,要调用此接口可以这么写:

// 第一种方式
public Object handler1(String ms) {
    return (new MyInterface() {
        @Override
        public Object handler(String s) {
            // 在这里做一些加工处理
            s += " hello world";
            return s;
        }
    }).handler(ms);
 }
 // 调用时如下
 public class Client {
 	public static void main(String[] args) {
 		String s = "Google";
 		System.out.println((new Client()).handler1(s));
 	}
 }

// 第二种方式
//可以先定义一个方法
public Object handler2(String s, MyInterface myInterface) {
   return myInterface.handler(s);
}

// 客户端调用方式
public class Client {
	public static void main(String[] args) {
		String s = "Hello World!";
		Object o = (new Client()).handler2(s, s1 -> {
            // 在这里做一些处理
            return s + " 你好!";
        });
        System.out.println(o);
	}
}

接口的定义规则请移步:
java8 函数式编程接口定义规则

发布了33 篇原创文章 · 获赞 24 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Myc_CSDN/article/details/87608839