Java8 Lamba表达式方法引用和构造器引用

1.方法引用包含三种:

(1)对象::函数名

(2)类::静态函数名

(3)类::函数名

ps.

a. lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值是一致的。

b.(3)对形参有要求,形参1和形参2在lambda表达式中形参1调用某函数,某函数形参是形参2。

2.构造器引用

调用构造器参数列表要与函数式接口抽象方法参数一致。

3.数组引用

import java.util.*;
import java.util.function.*;

/**
 * Created by zhangtuo on 2017/7/16.
 */
public class TestLambda {

    /**
     * 1.方法引用:
     *   NO.1 对象::实例方法名
     */
    public void test1() {
        Entity entity = new Entity();
        Consumer<Integer> con = (x)->entity.setX(x);
        Consumer<Integer> con2 = entity::setX;
        Consumer<Integer> con3 = new Entity()::setX;
        con.accept(23);
        con2.accept(23);
    }

    /**
     * 1.方法引用:
     *   NO.2 类::静态函数名
     */
    public void test2() {
        Comparator<Integer> com = (x, y)->Integer.compare(x, y);
        Comparator<Integer> com2 = Integer::compare;
        com.compare(1,2);
        com2.compare(1,2);
    }

    /**
     * 1.方法引用:
     *   NO.3 类::函数名(形参1和形参2在lambda表达式中形参1调用某函数,某函数形参是形参2)
     */
    public void test3() {
        BiPredicate<String, String> bp = (x, y)->x.equals(y);
        BiPredicate<String, String> bp2 = String::equals;
        bp2.test("x","y");

        BiFunction<Entity, Entity, Integer> bf = (x,y)->x.compare(y);
        bf.apply(new Entity(), new Entity());
        BiFunction<Entity, Entity, Integer> bf2 = Entity::compare;
        bf2.apply(new Entity(2), new Entity(3));
    }

    /**
     * 2.构造器引用:空构造器
     */
    public void test5() {
        Supplier<ArrayList> sup = ()->new ArrayList<>();
        Supplier<ArrayList> sup2 = ArrayList::new;
        sup.get();
        sup2.get();
    }

    /**
     * 2.构造器引用:带参数构造器
     */
    public void test6() {
        Function<Integer, ArrayList> fun = (x)->new ArrayList(x);
        Function<Integer, ArrayList> fun2 = ArrayList::new;
        fun.apply(2);
        fun2.apply(2);

        BiFunction<Integer, Integer, Entity> bf = Entity::new;
        bf.apply(1,2);
    }

    /**
     * 3.数组引用
     */
    public void test7() {
        Function<Integer, String[]> fun = (x)->new String[x];
        Function<Integer, String[]> fun2 = String[]::new;
    }
}

class Entity {
    int x;
    int y;
    Entity() {
    }
    Entity(int x) {
        this.x = x;
    }
    Entity(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public Integer compare(Entity entity) {
        if (entity != null)
            return 1;
        return 0;
    }

}

 

转载于:https://my.oschina.net/zhangtuoDMU/blog/1475722

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值