1、Lambda表达式

文章目录:
1.Lambda表达式
2.方法的引用和构造器的引用
3.Stream
4.新时间日期API
5.Optional类

一、Lambda表达式基础语法

java8引入了一个新的操作符 “->” 改操作符称为箭头操作符 或 Lambda操作符。
箭头操作符将 Lambda 表达式拆分成两部分:

  • 左侧:Lambda表达式的参数列表。
  • 右侧:Lambda表达式中所需执行的功能,即Lambda体。

语法:

  1. 一个括号内用逗号分隔的形式参数,参数是函数式接口里面方法的参数。
  2. 一个箭头符号:->
  3. 方法体,可以是表达式和代码块,方法体函数式接口里面方法的实现,如果是代码块,则必须用{}来包裹起来,且需要一个return 返回值,但有个例外,若函数式接口里面方法返回值是void,则无需{}。

语法格式一:

  • 无参数,无返回值:
    @Test
	public void test1(){
		int num = 0;//jdk 1.7 前,必须是 final
		Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println("Hello World!" + num);
			}
		};
		r.run();
		
		System.out.println("-------------------------------");
		
		Runnable r1 = () -> System.out.println("Hello Lambda!");
		r1.run();
	}

输出结果:

Hello World!0
-------------------------------
Hello Lambda!

语法格式二:

  • 有一个参数,无返回值(如果只有一个参数,小括号可以省略不写。):
    @Test
    public void test01(){
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("积极上进!");
    }

输出结果:

积极上进!

语法格式三

  • 有两个以上的参数,有返回值,并且Lambda体中有多条语句(必须用{}括起来)。
    @Test
    public void test05(){
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
        com.compare(1,5);
    }

输出结果:

函数式接口

语法格式四

  • 若Lambda体中只有一条语句,return和大括号都可以省略不写。
    @Test
    public void test03(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        int compare = com.compare(5, 100);
        System.out.println(compare);
    }

输出结果:

-1

语法格式五

  • Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出类型数据,即“类型推断”。
(Integer x, Integer y) -> Integer.compare(x, y)

总结:

  • 左右遇一括号省
  • 左侧推断类型省

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

  • 函数式接口

首先是一个接口,然后就是在这个接口里面只能有一个抽象方法。
这种类型的接口也称为SAM接口,即Single Abstract Method interfaces。

可以使用注解@FunctionalInterface修饰,检查是否是函数式接口。

@FunctionalInterface
public interface MyFun {
    public Integer getValue(Integer num);
}
//需求:对一个数进行运算
	@Test
	public void test6(){
		Integer num = operation(100, (x) -> x * x);
		System.out.println(num);
		
		System.out.println(operation(200, (y) -> y + 200));
	}
	
	public Integer operation(Integer num, MyFun mf){
		return mf.getValue(num);
	}

输出结果:

10000
400

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

1. Consumer : 消费型接口(有参,无返回值)

void accept(T t);

2. Supplier : 供给型接口(无参,有返回值)

T get();

3. Function<T, R> 函数型接口(有参,有返回值):

R apply(T t);

4. Predicate : 断言型接口(用于判断,有参,返回boolean类型):

boolean test(T t);

示例(点击上方超链接跳转到对应示例)

    /**
     * 1、Consumer<T> : 消费型接口(有参,无返回值)
     */
    @Test
    public void test01(){
        happy(1000, (x) -> System.out.println("吃喝玩乐" + x +"元!"));
    }
    public void happy(double mon, Consumer<Double> con){
        con.accept(mon);
    }

运行结果:

吃喝玩乐1000.0元!

    /**
     *  2、Supplier<T> : 供给型接口(无参,有返回值)
     *  需求:产生指定个数的整数,并放入集合中。
     */
    @Test
    public void test02(){
        List<Integer> numList = getNumList(5, () -> (int)(Math.random() * 100));
        for (Integer integer : numList) {
            System.out.println(integer);
        }
    }
    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> newList = new ArrayList<>();
        for(int i = 0; i < num; i++){
            Integer n = sup.get();
            newList.add(n);
        }
        return newList;
    }

运行结果:

40
40
85
82
36

    /**
     * 3、Function<T, R> 函数型接口(有参,有返回值):
     *  需求:用于处理字符串(取字符串[2,4))
     */
    @Test
    public void Test03(){
        String newStr = strHandler("中国山东青岛", (str) -> str.substring(2, 4));
        System.out.println(newStr);
    }
    public String strHandler(String str, Function<String,String> fun){
        return fun.apply(str);
    }

运行结果:

山东

    /**
     *  4、Predicate<T> : 断言型接口(用于判断):
     *  将满足条件的字符串(字符串长度大于3的),放入集合中
     */
    @Test
    public void test04(){
        List<String> list = Arrays.asList("Hello", "World", "ok", "a", "true");
        List<String> newList = filterStr(list, (str) -> str.length() > 3);
        for (String str : newList) {
            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;
    }

运行结果:

Hello
World
true

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值