您的位置:首页 > 编程语言 > Java开发

JAVA新特性(1)Lambda表达式

2019-05-16 11:38 507 查看
  1. lambda: In programming languages such as Lisp, Python and Ruby lambda is a oparator used to denote anonymous functions or closures , following the usage of lambda calculus
  2. Lambda表达式的基本语法:(argument)-> (body)
    body: expression  or   statement{}
    (param1,param2,param3)-> {
    }
  3. 函数式接口
    1)函数式接口的实例可以由lambda表达式,方法引用,构造方法引用来创建。
    2)如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口。
    3)如果我们在某个接口上声明了FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该接口。
    4)如果某个接口只有一个抽象方法,但是我们并没有给该接口申明FunctionInterface注解,那么编译器依旧会将该接口看做是函数式接口。
  4.  在接口中如果也有方法的实现(1.8新增),为default方法。此外,在接口中还可以定义static方法
  5. 在将函数作为一等公民的语言中,Lambda表达式的类型是函数。但在Java中,Lambda表达式是对象,它们必须依附于一类特别的对象类型----函数式接口(functional interface)。 
  6. 几种方式的实现示例:
    [code]public class Test1 {
    public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
    for(int i = 0;i < list.size(); i++){
    System.out.println(list.get(i));
    }
    System.out.println("------------");
    for(Integer i : list){//外部迭代
    System.out.println(i);
    }
    System.out.println("------------");
    //通过Lambda表达式
    list.forEach(i -> System.out.println(i));//内部迭代
    //可以不声明类型,由编译器推断出来,(list中的每个元素为Integer类型)
    list.forEach((Integer i) -> System.out.println(i));
    System.out.println("------------");
    list.forEach(System.out::println);//通过方法引用创建函数式接口的实例
    }
    }

     
  7. Java Lambda 表达式是一种匿名函数;它是没有声明的方法,即没有访问修饰符、返回值声明和名字。
  8. Lambda表达式的作用:传递行为,而不仅仅是值
  9. 基本接口介绍与应用:接口位于rt.jar包下java.util.function包下
  10. function接口以及BiFunction接口的使用与理解:
    1)R apply(T t);函数:对给定参数实施此函数,返回函数结果
    [code]    @Test
    public void Test1(){
    FunctionTest functionTest = new FunctionTest();
    
    Function<Integer,Integer> function = value -> value*value;//也可以单独定义好
    System.out.println(functionTest.compute(1, function));
    
    System.out.println(functionTest.compute(1, value->5*value));
    //使用lambda表达式定义行为
    System.out.println(functionTest.convert(2, value->value + "Hello"));
    }
    //Function<T,R>为一个函数式接口:将这个函数用到指定的参数上;其中T为函数参数,R为函数返回值
    //compute与convert均为高阶函数:以一个函数作为自己的参数
    public int compute(int a, Function<Integer,Integer> function){
    int result = function.apply(a);
    return result;
    }
    public String convert(int a, Function<Integer, String> function){
    return function.apply(a);
    }

    2)复合函数的应用:
          BiFunction接口中  :R apply(T t, U u);函数:接收两个参数,对给定参数实施此函数,返回函数结果。

  11. [code]    @Test
    public void Test2(){
    System.out.println(calculate1(1, value->value*value,
    value->value+value));//结果:4
    System.out.println(calculate2(1, value->value*value,
    value->value+value));//结果:2
    }
    //    先function2,再function1
    public int calculate1(int a, Function<Integer,Integer> function1,
    Function<Integer,Integer> function2){
    return function1.compose(function2).apply(a);
    //在Function接口中的default方法:
    // default <V> Function<V, R> compose(Function<? super V, ? extends T> before):
    // 对Function的输入参数先应用before函数,再应用此函数
    }
    //    先function1,再function2
    public int calculate2(int a, Function<Integer,Integer> function1,
    Function<Integer,Integer> function2){
    return function1.andThen(function2).apply(a);
    //在Function接口中的default方法:
    // default <V> Function<V, R> andThen(Function<? super V, ? extends T> after):
    // 对Function的输入参数先应用此函数,再应用after函数
    }
    
    @Test
    public void TestBiFunction(){
    System.out.println(calculate3(1, 2, (v1,v2)->v1*v2));//2
    System.out.println(calculate3(1, 2, (v1,v2)->v1/v2));//0
    System.out.println(calculate3(1, 2, (v1,v2)->v1+v2));//3
    System.out.println(calculate3(1, 2, (v1,v2)->v1-v2));//-1
    System.out.println(calculate4(1, 2, (v1,v2)->v1+v2,v -> v*v ));//9
    }
    public int calculate3(int a, int b, BiFunction<Integer,Integer,Integer> biFunction){
    return biFunction.apply(a, b);//biFunction接收两个参数
    }
    public int calculate4(int a, int b, BiFunction<Integer,Integer,Integer> biFunction1,
    Function<Integer,Integer> function2){
    return biFunction1.andThen(function2).apply(a, b);
    }

    3)实例应用
     

    [code]    @Test
    public void PersonTest1(){
    Person person1 = new Person("liu", 12);
    Person person2 = new Person("Ze", 22);
    Person person3 =  new Person("wei", 21);
    Person person4 = new Person("ze", 16);
    Person person5 = new Person("ze", 17);
    
    List<Person> list = Arrays.asList(person1,person2,person3,person4,person5);
    List<Person> resultByname = getPersonByUsername("ze", list);
    List<Person> resultByage = getPersonByAge(20, list);
    resultByname.forEach(person -> System.out.println(person.getAge()));
    resultByage.forEach(person -> System.out.println(person.getName()));
    
    List<Person> resultByage2 = getPersonByAge2(20,list,
    (age,personlist)-> personlist.stream().filter
    (person -> person.getAge()>age).collect(Collectors.toList()));
    resultByage2.forEach(person -> System.out.println(person.getName()));
    
    }
    //    在集合中查找特定名字的Person集合
    public List<Person> getPersonByUsername(String username, List<Person> persons){
    return persons.stream().filter(person -> person.getName().equals(username)).
    collect(Collectors.toList());
    }
    //    在集合中查找大于指定age的Person集合
    public List<Person> getPersonByAge(Integer userage,List<Person> persons){
    BiFunction<Integer,List<Person>,List<Person>> biFunction =
    (age,personList)->
    persons.stream().filter(person -> person.getAge() > age).
    collect(Collectors.toList()) ;
    return biFunction.apply(userage, persons);
    }
    //    另一种方式实现,用户使用时才传进来需要的动作,更加灵活
    public List<Person> getPersonByAge2(Integer userage,List<Person> persons,
    BiFunction<Integer,List<Person>,List<Person> > biFunction){
    return biFunction.apply(userage, persons);
    }

     

  12. predicate接口功能与理解:对一个参数进行谓语
    boolean test(T t);函数:对给定的参数进行谓语 判断,判断结果为bool类型(true或false)
  13. [code]   @Test
    public void predicateTest() {
    Predicate<String> predicate = s -> s.length() > 5;
    System.out.println(predicate.test("liuzwe"));//true
    }
    
    @Test
    public void predicationTest2() {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    conditionFilter(list, value -> value % 2 == 0);//打印偶数
    conditionFilter(list, value -> value % 2 != 0);//打印奇数
    conditionFilter(list, value -> value > 5);
    System.out.println("--------------------------");
    conditionFilter(list, value -> true);
    
    System.out.println("--------------------------");
    conditionFilter2(list, value -> value % 2 == 0, value -> value > 5);
    
    //Predicate中的静态方法:static <T> Predicate<T> isEqual(Object targetRef):判断两个参数是否相等
    System.out.println(Predicate.isEqual("test").test("test"));
    }
    
    public void conditionFilter(List<Integer> list, Predicate<Integer> predicate) {
    for (Integer integer : list) {
    if (predicate.test(integer))
    System.out.println(integer);
    }
    }
    //Predicate接口中default Predicate<T> and(Predicate<? super T> other)的使用(逻辑与):
    // 同时满足other以及此Predicate
    // 还有or(逻辑或),negate(非)
    public void conditionFilter2(List<Integer> list, Predicate<Integer> predicate1,
    Predicate<Integer> predicate2) {
    for (Integer integer : list) {
    if (predicate1.and(predicate2).test(integer)) {
    System.out.println(integer);
    }
    }
    }

     

  14. Supplier接口:无参数,有返回值
    T get();函数:返回结果
    [code]    @Test
    public void Test1(){
    Supplier<String> stringSupplier = ()->"hello world";
    System.out.println(stringSupplier);
    //com.learn.jdk8.SupplierTest$$Lambda$1/1982791261@3830f1c0
    System.out.println(stringSupplier.get());//hello world
    }
    @Test
    public void Test2(){
    Supplier<Student> studentSupplier = ()->new Student();
    System.out.println(studentSupplier.get());//com.learn.jdk8.Student@39ed3c8d
    Supplier<Student> supplier = Student::new;
    System.out.println(supplier.get().getName());//liu
    }
    }
    class Student{
    private String name = "liu";
    private int age = 21;
    public Student() {
    }
    public String getName() {
    return name;
    }
    public int getAge() {
    return age;
    }
    public Student(String name, int age) {
    this.name = name;
    this.age = age;
    }
    public void setName(String name) {
    this.name = name;
    }
    public void setAge(int age) {
    this.age = age;
    }

     

  • public interface BinaryOperator<T> extends BiFunction<T,T,T>接口,接收两个参数,有返回值,且他们类型都相同;
    继承自BiFunction接口(可用BiFunction中的apply)
    同时提供public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) 静态方法,可自定义比较器,返回较小的一个元素
    [code]    public void Test1(){
    System.out.println(compute(12,1,(v1,v2) -> v1-v2));//11
    System.out.println(MyCompare(12,10,(v1,v2)->v2-v1));//10
    
    //比较长度
    System.out.println(MyCompareString("liu", "ze", (a,b)->a.length()-b.length()));
    //输出liu
    
    //比较首字母
    System.out.println(MyCompareString("liu", "ze", (a,b)->a.charAt(0)-b.charAt(0)));
    //输出ze
    }
    public int compute(int a, int b, BinaryOperator<Integer> binaryOperator){
    return binaryOperator.apply(a, b);
    }
    public int MyCompare(int a, int b, Comparator<Integer> comparator){
    return BinaryOperator.maxBy(comparator).apply(a, b);
    }
    public String MyCompareString(String a, String b, Comparator<String> comparator){
    return BinaryOperator.maxBy(comparator).apply(a, b);
    }

    基本接口

    表达

    接口方法

    Consumer

    一个输入,没有输出

    void accept(T t);

    Function

    一个输入,一个输出

    R apply(T t);

    Predicate

    一个输入,谓语,输出为bool型

    boolean test(T t);

    Supplier

    没有输入,一个输出

    T get();



     

     

突然想法:看社会主流;还看受众多少,这个品格或爱好,是不是大多数人所喜欢的,或羡慕的,这样就成功了一半。一定要积极主动的表现自我。
那么就会涉及到价值取舍的问题:
软件开发,科研等等逻辑思维与理性思维的不断强化,会不利于感性或人的一些质朴的情感的发挥和表达,与人的沟通交流变少,在与人交往的思维方面也会钝化。
可以看到那些整天游历四方的人的状态,感性的丰富,反过来如果能将此应用于工作(经济来源),则他们可以不断的在此方面加强,又正向作用于人际生活。受人所爱而同时收获很多。
当然活的开心有两方面的内容:做着自己喜欢的事,生活目标达到了自己的要求(包含生活水平,别人自己的认可,合适的伴侣,自己的欲望的满足等)。生活目标这一块很重要,不然即便做着自己喜欢的事,仍然感到失落与不满。

 

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: