java lambda表达式

lambda表达式概览

package com.imekaku;


import org.junit.Test;

import java.util.*;

/**
 * Created by lee on 2017/6/8.
 */
public class TestLambda {

    List<Employee> list = Arrays.asList(
            new Employee("张三", 23),
            new Employee("李四", 30),
            new Employee("王五", 28)
    );

    // 过滤员工年龄大于25的员工
    public List<Employee> filterEmployee1(List<Employee> list) {
        List<Employee> employees = new ArrayList<>();
        for (Employee emp : list) {
            if (emp.getAge() > 25) {
                employees.add(emp);
            }
        }

        return employees;
    }

    public List<Employee> filterEmployee2(List<Employee> list, MyPredicate<Employee> myPredicate) {
        List<Employee> employees = new ArrayList<>();
        for (Employee emp : list) {
            if (myPredicate.filter(emp)) {
                employees.add(emp);
            }
        }

        return employees;
    }

    @Test
    public void show() {
        List<Employee> employees = filterEmployee1(list);
        for (Employee emp : employees) {
            System.out.println(emp);
        }

        System.out.println("--------------**使用策略模式**--------------");
        List<Employee> employees1 = filterEmployee2(list, new FileEmployeeByAge());
        for (Employee emp : employees1) {
            System.out.println(emp);
        }

        System.out.println("-----------------**使用lambda表达式**--------------------");
        List<Employee> employees2 = filterEmployee2(list, (e) -> e.getAge() > 25);
        employees2.forEach(System.out::println);
    }
}

class Employee {
    public String name;
    public int age;

    public Employee() {
    }

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

interface MyPredicate<T> {
    boolean filter(T t);
}

class FileEmployeeByAge implements MyPredicate<Employee>{

    @Override
    public boolean filter(Employee employee) {
        return employee.getAge() > 25;
    }
}

lambda表达式基础语法

lambda表达式语法基础:lambda表达式需要”函数式接口”的支持

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

左侧:lambda表达式的参数列表

右侧:lambda表达式中所需执行的功能,即lambda 体

lambda表达式的几种情况

package com.imekaku;

import org.junit.Test;

import java.util.Comparator;
import java.util.function.Consumer;

/**
 * Created by lee on 2017/6/8.
 */
public class TestLambda2 {

    // 无参数,无返回值
    @Test
    public void test1() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World!");
            }
        };

        runnable.run();

        System.out.println("------------使用lambda表达式-----------");

        // 左边是接口的参数列表,右边是抽象方法的实现
        Runnable runnable1 = () -> System.out.println("Hello Lambda!");
        runnable1.run();
    }

    // 有参数,无返回值
    @Test
    public void test2() {
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("Hello Lambda!");

        Consumer<String> con1 = x -> System.out.println(x);
        con.accept("Hello Lambda!");
    }

    // 有多个参数,并且有返回值,需要写大括号,并且有多条语句
    @Test
    public void test3() {
        Comparator<Integer> com = (x, y) -> {
            System.out.println("表示有多条语句");
            System.out.println("Hello Lambda!");
            return Integer.compare(x, y);
        };
        int result = com.compare(30, 20);
        System.out.println(result);
    }

    // 有多个参数,并且有返回值,只有一条语句,那么可以省略return和大括号
    @Test
    public void test4() {
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        int result = com.compare(30, 20);
        System.out.println(result);
    }

    // lambda表达式必须依赖于接口
    @Test
    public void test5() {
        MyFunction<String> myFunction = (x) -> x + " World";
        String result = myFunction.func("Hello");
        System.out.println(result);
    }

    // 使用策略模式
    @Test
    public void test6() {
        Integer i = operator(10, (x) -> x * x);
        System.out.println(i);
    }

    private Integer operator(Integer num, MyFunction<Integer> myFunction) {
        return myFunction.func(num);
    }
}

@FunctionalInterface
interface MyFunction<T> {
    T func(T t);
}

lambda表达式练习

package com.imekaku;

import org.junit.Test;

import java.util.*;

/**
 * Created by lee on 2017/6/9.
 */
public class TestLambda3 {

    List<Employee> list = Arrays.asList(
            new Employee("AA", 23),
            new Employee("BB", 30),
            new Employee("FF", 28)
    );

    @Test
    public void test1() {
        Collections.sort(list, ((o1, o2) -> {
            if (o1.getAge() == o2.getAge()) {
                return o1.getName().compareTo(o2.getName());
            }
            return Integer.compare(o1.getAge(), o2.getAge());
        }));

        Iterator<Employee> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    // 将小写字母转换成大写字母
    @Test
    public void test2() {
        String result = castWord("hello world", (x) -> x.toUpperCase());
        System.out.println(result);

        String result1 = castWord("    hello world   ", (x) -> x.trim());
        System.out.println(result1);
    }

    private String castWord(String src, MyFunction2<String> myFunction2) {
        return myFunction2.cast(src);
    }

    @Test
    public void test3() {
        Long result = operator(1234L, 5678L, (x, y) -> x * y);
        System.out.println(result);
    }

    private Long operator(Long d1, Long d2, MyFunction3<Long, Long> myFunction3) {
        return myFunction3.handler(d1, d2);
    }
}

@FunctionalInterface
interface MyFunction2<T> {
    T cast(T t);
}

@FunctionalInterface
interface MyFunction3<T, R> {
    R handler(T t1, T t2);
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部