java8的lambda表达式

java8--函数式接口,以及和Lambda表达式的关系

2019-03-08  本文已影响0人  哈哈_dfde

一:函数式接口
函数式接口其实本质上还是一个接口,但是它是一种特殊的接口:SAM类型的接口(Single Abstract Method)。
jdk8的lambda表达式的函数式接口主要有:


image.png

二:Predicate<T>
确定入参为T的参数,是否满足方法中的条件。
涉及到的lambda表达式方法主要是 filter(Predicate<T> predicate);
demo:

  import java.util.Arrays;
  import java.util.List;
  import java.util.function.Predicate;

  public class PredicateDemo {
        public static void main(String[] args) {
    //给list添加参数
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.println("输出所有参数字:");
        eval(list, n -> true);
        System.out.println("\n输出能被2整除的数字:");
        eval(list, n -> n%2==0);
        System.out.println("\n输出大于3的数字:");
        eval(list, n-> n > 3 );
   }

//自定义方法
   public static void eval(List<Integer> list, Predicate<Integer> predicate) {
        for(Integer n: list) {        
           if(predicate.test(n)) {
               //可以将满足条件的参数返回,这里只做输出
               System.out.print(n + " ");
           }
        }
     }
   }

2 Function<T,R>
对类型T的入参,返回类型是R的对象,这个函数主要是调用内部的apply方法,T apply(R)
主要针对的stream方法:map
demo

 public class Operation{
     public static final int addOne(int a){
     return a+1;
     } 
public static int oper(int a, Function<Integer,Integer> action){
     return action.apply(a);
}
public static void main(String[] args){
  int x = 1;
  int y = oper(x,x -> addOne(x));//这里可以换成方法引用的写法 int y = 
  oper(x,Operation::addOne)
  System.out.printf("x= %d, y = %d", x, y); // 打印结果 x=1, y=2
  y = oper(x, x -> x + 3 ); // y = 4
  y = oper(x, x -> x * 3 ); // y = 3    
   }
 }

3 Consumer接口,顾名思义将T为入参的对象进行消费,无返回。

  public static void main(String[] args) {
    Consumer<String> printString = s -> System.out.println(s);
    printString.accept("helloWorld!");
    //控制台输出 helloWorld!
  }

4 Supplier<T>接口 ,返回对象为T的方法,没有入参

      public static void main(String args[]){
          Supplier<String> getInstance = () -> "HelloWorld!";
          System.out.println(getInstance.get());
      } 
上一篇 下一篇

猜你喜欢

热点阅读