1.java8以后出现了 函数式编程
在java中体现为 一个接口对应一个抽象方法;
使用注解@FunctionalInterface 声明为 函数式抽象方法
lambda表达式是一种新的语言功能,允许把函数作为参数传入方法内(好多高级语言都支持),lambda表达式可以简化开发代码
一 声明函数接口
package com.xiaodu.java8Test.lambda.function;
public class TestJava8Function {
/**
* 声明两个int参数的函数
*/
@FunctionalInterface
interface Function01{
int function01(int a, int b);
}
/**
* 声明多个int参数的函数
*/
@FunctionalInterface
interface Function02{
int function02(int... a);
}
/**
* 声明一个string参数的函数
*/
@FunctionalInterface
interface Function03{
String function03(String mess);
}
}
二 调用测试
1. function01
package com.xiaodu.java8Test.lambda.function;
import org.junit.Test;
import com.xiaodu.java8Test.lambda.function.TestJava8Function.Function01;
public class TestFunction01 {
/**
* 测试function01 函数接口
*/
@Test
public void TFunction01() {
/**
* 求和
* 参数带类型的
*/
Function01 f01 = (int a, int b ) -> a+b;
System.out.println(f01.function01(12, 12));//24
/**
* 求差
* 不带参数类型的,java8之后可以进行类型推断
*/
f01 = (a,b) -> a-b;
System.out.println(f01.function01(3, 1));//2
/**
* 求乘积
* 带返回值的
*/
f01 = (a,b) -> {
return a*b;
};
System.out.println(f01.function01(2, 3));//6
}
}
2 测试function02
/**
* 测试function02
*/
@Test
public void TestFuncion02() {
/**
* 求和
*/
Function02 f02 = (int[] a) -> {
int sum = 0;
for (int i : a) {
sum += i;
}
return sum;
};
System.out.println(f02.function02(new int[]{1,2,3}));
/**
* 求偶数和
*/
f02 = (int[] a) ->{
int sum = 0;
for(int i=0;i<a.length;i++){
if(a[i]%2 ==0){
sum +=a[i];
}
};
return sum;
};
System.out.println(TestFunction01.getNumber(new int[]{2,4,5},f02));
}
public static Integer getNumber(int[] a,Function02 f02){
if(a !=null) {
return f02.function02(a);
}
return 0;
}
测试function03
@Test
public void TestFunction03() {
/**
* 单个参数可以不带()
*/
Function03 f03 = mess -> {return mess + " Lambda";};
System.out.println(f03.function03("xiaodu"));
/**
* 截取字符串
*
*/
f03 = mess ->{
mess = mess.substring(0,mess.length()/2);
return mess;
};
System.out.println(f03.function03("123 abc"));
使用Lambda 简化匿名内部类
/**
* 使用Lambda 简化 匿名内部类
*/
@Test
public void TestThread() {
// 开启一个线程 使用匿名内部类
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println("new Runnable ... " + i);
}
}
}).start();
// 使用Lambda 开启线程
new Thread(() -> {
for(int i=0;i<5;i++) {
System.out.println("Lambda start ..." + i);
}
}).start();
// 拆分Lambda启动线程
// 1. 创建Runnable 的lambda表达式
Runnable r = () -> {
for(int i=0;i<5;i++) {
System.out.println("Runnable start ..." + i);
}
};
new Thread(r).start();
}
查看java8之后的runnable
测试排序
/**
* 使用Lambda 进行排序
*/
@Test
public void comparator() {
List<Integer> asList = Arrays.asList(10,4,5,7,8,9);
// 使用Collections 工具类 排序
Collections.sort(asList);
System.out.println(asList);
// 自定义倒序
Collections.sort(asList, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(o1 > o2)
return -1;
return 1;
}
});
System.out.println(asList);
// 使用Lambda 排序
Collections.sort(asList,(a,b) -> {
if(a>b) return 1;
return -1;
}
);
System.out.println(asList);
}