java8 lambda表达式 函数式编程

java 8引入了 lambda表达式 他主要用于简化代码 比如我们平时都是使用匿名类来实现一个接口 有了lambda 我们只需要考虑实现接口方法就行了 前提是此接口只能有一个抽象方法 在这里java8 加入了接口可以实现具体的方法 方法前必须使用defalut 关键词修饰 在被default关键词修饰的方法不做为lambda表达式的实现 也就是说 一个接口可以有多个default方法但必须只有一个抽象方法才能被lambda 使用。

下面介绍lambda语法
()代表参数
在这里插入图片描述
-> 连接符
{}方法体

1.有惨无返回的实现
(a)->{System.out.println(a)}
1个参数可以省略参数括号 方法体也一样 简化过后
a->System.out.print();
2.有惨有返回
(a,b)->{return a+b}
return 可以省略
(a,b)->a+b;
3.无惨无返回
()->System.out.print(“我被执行了”);
4.无惨有返回
()-> “我是返回值”;

下面演示lambda的使用

创建一个有惨无返回方法的接口
@FunctionalInterface
public interface argnone {
void test(String aa);
}
这里使用@FunctionalInterface注解表示这是一个函数式接口

     argnone one1=a->System.out.print(a);
     argnone one2=System.out::println;
     one1.test("我被执行了1");
     one2.test("我被执行了2");
     这有两种实现第二种看不懂没关系后面会提到

创建一个无惨有返回的接口
@FunctionalInterface
interface argff{
String test();
}
argff test2=()->“返回值”;

创建有惨有返回接口
@FunctionalInterface
interface argff2{
String test(String aa);
}
argff test2=(aa)->“返回值”+aa;

lambda表达式还可以引用已经实现了的方法

创建接口

@FunctionalInterface
public interface argnone {
void test(String aa);
}

public class lambda {
public static void main(String [] args) {

    1.   argnone cc=a->vv(a);
     2.  argnone ss=lambda::vv;
}

 private static void vv(String ss){
    System.out.println("ll"+ss);
}

}
这有两种方法

引用外部的类方法
class sts{

sts(){
    System.out.print("无惨构造方法");
}
sts(int a){
    System.out.println("有惨构造方法"+a);
}
public void bs(String ss){
    System.out.println("ll"+ss);
}

}

//argnone nn=new sts()::bs;
如果是静态方法还可以这样
//argnone nn=sts::bs;

lambda还提供了一些函数接口
他们都在java.util.function包里

1.Function<T, R>:接受一个参数T,返回结果R

2.Predicate:接受一个参数T,返回boolean

3.Supplier:不接受任何参数,返回结果T

4.Consumer:接受一个参数T,不返回结果

5.UnaryOperator:继承自Function<T, T>,接受一个参数T,返回相同类型T的结果

6.BiFunction<T, U, R>:接受两个参数T和U,返回结果R

7.BinaryOperator:继承自BiFunction<T, T, T>,接受两个相同类型T的参数,返回相同类型T的结果

8.Runnable:实际上是不接受任何参数,也不返回结果

9.Comparable:实际上是接受两个相同类型T的参数,返回int

10.Callable:不接受任何参数,返回结果V

遍历list
public class lamvdalists {
public static void main(String[] args) {
List ints=new ArrayList();
Collections.addAll(ints,1,4,3,5,6,7,8,3,4);
ints.forEach((a)->System.out.print(a));
System.out.println("");
ints.forEach(System.out::print);

}

}

对list排序
public static void main(String[] args) {

    List<person> list=new ArrayList<person>();
    list.add(new person("张三",10));
    list.add(new person("李四",12));
    list.add(new person("王二狗",3));
    list.add(new person("淑芬",6));
    list.add(new person("翠花田狗",15));

    list.sort(
            (arg1,arg2)->{return  arg2.age-arg1.age;}
    );
    for(person ls:list){
        System.out.println(ls.toString());
    }


}

版权声明:本文为qq_28422443原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。