Java8新特性之lambda表达式

简介

Java8带来的新特性之一Lambda表达式,又称之为函数式编程,核心思想是将面向对象中的传递对象变为传递行为

语法

expression = (variable) -> anction
eg: int sum = (x,y) ->x+y;

  • variable:相当于一个变量,可以有多个
  • action:代码逻辑部分,可以是一行也可以是一个代码段
package com.jdk8;

public class Student {


    private String name;
    private String city;
    private int age;
    private String sex;


    public String getName() {
        return name;
    }

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

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}
package com.jdk8;

public interface TestInterface<T> {

    Boolean test(T param);
}

package com.jdk8;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class TesFunction {

    @Test
    public void testLambda(){
    
     
        //3.有参,有返回值
        func((Integer x)->{
            System.out.println("Hello,world"+x);
            return true;
        });
        //
        List<Student> stuList = new ArrayList<Student>();
        for(int i = 0 ;i < 5 ;i++){
            Student s = new Student();
            s.setName("李磊");
            s.setAge(20);
            s.setCity("China");
            s.setSex("man");
            stuList.add(s);
        }
        int cout = (int) stuList.stream().filter((student -> student.getCity().equals("China"))).count();
        System.out.println(cout);

    }
    private void func(TestInterface<Integer> functionInterface){
        int x =1;
        functionInterface.test(x);
    }
}

posted @ 2018-08-27 22:50  脑白金  阅读(154)  评论(0编辑  收藏  举报