Java8新特性之Lambda表达式和内置接口

Lambda表达式

1、为什么使用Lambda表达式

 Lambda 是一个匿名函数,我们可以把 Lambda表达式理解为是一段
 可以传递的代码(将代码像数据一样进行传递)。
 可以写出更简洁、更灵活的代码。
 作为一种更紧凑的代码风格, 使Java的语言表达能力得到了提升。

2、语法

2.1 基础语法


 Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
 箭头操作符将 Lambda 表达式拆分成两部分:
 
左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体

 * 
 * 上联:左右遇一括号省
 * 下联:左侧推断类型省
 * 横批:能省则省
 * 
2.1.1
  • 语法格式一:无参数,无返值
    () -> System.out.println("Hello Lambda!");
    在这里插入图片描述
2.1.2
  • 语法格式二:有一个参数,并且无返回值
    (x) -> System.out.println(x)
    在这里插入图片描述
2.1.3
  • 语法格式三:若只有一个参数,小括号可以省略不写
    x -> System.out.println(x)
  • 一般按照第二个种格式来在这里插入图片描述
2.1.4
  • 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
 	Comparator<Integer> com = (x, y) -> {
 			System.out.println("函数式接口");
 			return Integer.compare(x, y);
 		};

在这里插入图片描述

2.1.5
  • 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
    Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
    在这里插入图片描述
2.1.6
  • 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
    (Integer x, Integer y) -> Integer.compare(x, y);

2.2、Lambda 表达式需要“函数式接口”的支持

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 
可以使用注解 @FunctionalInterface 修饰,可以检查是否是函数式接口


2.3 、方法引用与构造器引用

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
(实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!)
(可以将方法引用理解为 Lambda 表达式的另外一种表现形式) 
方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。
如下三种主要使用情况:
⚫ 对象::实例方法
⚫ 类::静态方法
⚫ 类::实例方法
2.3.1 方法引用
 (x) -> System.out.println(x);    
 // 等同于
 System.out::println
BinaryOperator<Double> binaryOperator = (x,y) -> Math.pow(x,y);
// 等同于
BinaryOperator<Double> binaryOperator1 = Math::pow;
 compare( (x,y) -> x.equals(y), "abc","abcde" )
 //等同于
 compare(String::equals,"abc","abcde")
@Test
    public void test() {
        PrintStream ps = System.out;
        Consumer<String> con = (str) -> ps.println(str);
        con.accept("Hello World!");

        System.out.println("--------------------------------");

        Consumer<String> con2 = ps::println;
        con2.accept("Hello Java8!");

        System.out.println("--------------------------------");

        Consumer<String> con3 = System.out::println;
        con3.accept("abcss");
    }

在这里插入图片描述

//对象的引用 :: 实例方法名
	@Test
	public void test2(){
		Employee emp = new Employee(101, "张三", 18, 9999.99);
		
		Supplier<String> sup = () -> emp.getName();
		System.out.println(sup.get());
		
		System.out.println("----------------------------------");
		
		Supplier<String> sup2 = emp::getName;
		System.out.println(sup2.get());
	}

在这里插入图片描述

//类名 :: 静态方法名
    @Test
    public void test4(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        int compare = com.compare(1, 2);
        System.out.println(compare);
        System.out.println("-------------------------------------");

        Comparator<Integer> com2 = Integer::compare;
    }

    @Test
    public void test3(){
        BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
        System.out.println(fun.apply(1.5, 22.2));

        System.out.println("--------------------------------------------------");

        BiFunction<Double, Double, Double> fun2 = Math::max;
        System.out.println(fun2.apply(1.2, 1.5));
    }
//类名 :: 实例方法名
	@Test
	public void test5(){
		BiPredicate<String, String> bp = (x, y) -> x.equals(y);
		System.out.println(bp.test("abcde", "abcde"));
		
		System.out.println("-----------------------------------------");
		
		BiPredicate<String, String> bp2 = String::equals;
		System.out.println(bp2.test("abc", "abc"));
		
		System.out.println("-----------------------------------------");
		
		
		Function<Employee, String> fun = (e) -> e.show();
		System.out.println(fun.apply(new Employee()));
		
		System.out.println("-----------------------------------------");
		
		Function<Employee, String> fun2 = Employee::show;
		System.out.println(fun2.apply(new Employee()));
		
	}

注意:
当需要引用方法的第一个参数是调用对象,并且第二个参数是需要引
用方法的第二个参数(或无参数)时:ClassName::methodName

2.3.2 构造器引用
  • 格式: ClassName::new
  • 与函数式接口相结合,自动与函数式接口中方法兼容。
    可以把构造器引用赋值给定义的方法,与构造器参数
    列表要与接口中抽象方法的参数列表一致!
//构造器引用
    @Test
    public void test6(){
        Supplier<Employee> sup = () -> new Employee();
        System.out.println(sup.get());

        System.out.println("------------------------------------");

		// 注意:这里的Employee中有多个构造器,那么具体调用的是哪个呢
		// 调用的是抽象方法,这里是Supplier中的方法的参数一致,因此调用的是无参
        Supplier<Employee> sup2 = Employee::new;
        System.out.println(sup2.get());
    }


在这里插入图片描述

 @Test
 	// 注意这里的参数,参数有几个,那么对应的实体中就要有对应的构造器
    public void test7(){
        Function<String, Employee> fun = Employee::new;

        BiFunction<String, Integer, Employee> fun2 = Employee::new;
    }

在这里插入图片描述

2.3.3 数组引用
  • 格式: type[] :: new
	//数组引用
	@Test
	public void test8(){
		Function<Integer, String[]> fun = (args) -> new String[args];
		String[] strs = fun.apply(10);
		System.out.println(strs.length);
		
		System.out.println("--------------------------");
		
		Function<Integer, Employee[]> fun2 = Employee[] :: new;
		Employee[] emps = fun2.apply(20);
		System.out.println(emps.length);
	}

在这里插入图片描述

3.练习

在这里插入图片描述

3.1

在这里插入图片描述
在这里插入图片描述在这里插入图片描述

3.2

在这里插入图片描述

@FunctionalInterface
public interface MyFunction {
    public String getValue(String str);
}
public String strHandler(String str,MyFunction myFunction) {
        return myFunction.getValue(str);
}
 @Test
public void test() {
	String trimStr = strHandler("\t\t\t 你好 ", (str) -> str.trim());
    System.out.print(trimStr);
}

在这里插入图片描述

3.3

在这里插入图片描述

@FunctionalInterface
public interface MyFunction1<T,R> {
    public R getValue(T t1,T t2);
}
@Test
public void test() {

	  long returnNum = operation(1L, 2L, (x, y) -> {
	      return x * y;
	  });

  	  System.out.println(returnNum);
  }

public Long operation(Long num1, Long num2, MyFunction1<Long,Long> myFunction) {
        return  myFunction.getValue(num1,num2);
}

在这里插入图片描述

4.四大内置核心函数式接口

Java8 内置的四大核心函数式接口:

		 Consumer<T> : 消费型接口
		 	void accept(T t);

		 Supplier<T> : 供给型接口
		  		T get(); 
		  		
		 Function<T, R> : 函数型接口
		  		R apply(T t);
  
		  Predicate<T> : 断言型接口
		  		boolean test(T t);
 

//Consumer<T> 消费型接口 :
	@Test
	public void test1(){
		happy(10000, (m) -> System.out.println("每次消费:" + m + "元"));
	} 
	
	public void happy(double money, Consumer<Double> con){
		con.accept(money);
	}

//Supplier<T> 供给型接口 :
	@Test
	public void test2(){
		List<Integer> numList = getNumList(10, () -> {
            return (int) (Math.random() * 100);
        });
		
		for (Integer num : numList) {
			System.out.println(num);
		}
	}
	
	// 需求:产生指定个数的整数,并放入集合中
	public List<Integer> getNumList(int num, Supplier<Integer> sup){
		List<Integer> list = new ArrayList<>();
		
		for (int i = 0; i < num; i++) {
			 list.add(supplier.get());
		}
		
		return list;
	}

在这里插入图片描述

	//Function<T, R> 函数型接口:
	@Test
	public void test3(){
		String newStr = strHandler("\t\t\t 你好   ", (str) -> str.trim());
        System.out.println(newStr);

        String subStr = strHandler("你好,我爱java", (str) -> str.substring(2, 5));
        System.out.println(subStr);
	}
	
	//需求:用于处理字符串
	public String strHandler(String str, Function<String, String> fun){
		return fun.apply(str);
	}

在这里插入图片描述

//Predicate<T> 断言型接口:
	@Test
	public void test4(){
		List<String> list = Arrays.asList("Hello", "Lambda", "www", "ok");
		List<String> strList = filterStr(list, (s) -> s.length() > 3);
		
		for (String str : strList) {
			System.out.println(str);
		}
	}
	
	//需求:将满足条件的字符串,放入集合中
	public List<String> filterStr(List<String> list, Predicate<String> pre){
		List<String> strList = new ArrayList<>();
		
		for (String str : list) {
			if(pre.test(str)){
				strList.add(str);
			}
		}
		
		return strList;
	}

在这里插入图片描述

注意:
还有其他的子接口
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值