Java8新特性。

常用函数接口:

函数式接口:

函数式接口在Java中是指:有且仅有一个抽象方法的接口(可以含其他方法)。

而Java中的函数式编程的体现就是Lambda。

@FunctionalInterface 注解:检测接口是否是函数式接口。

函数式接口的使用:一般可以作为方法的参数和返回值类型。

Lambda表达式有延迟执行的特点,可提高程序运行效率。

@java.lang.FunctionalInterface
public interface FunctionalInterface {
    public abstract void method();
}
public class Demo {
    //定义一个方法,参数使用函数式接口
    public static void show(FunctionalInterface myInter){
        myInter.method();
    }

    public static void main(String[] args) {
        //方法的参数是一个接口,所以可以传递接口的实现类
        show(new MyFunctionalInterfaceImpl());

        //也可以传递接口的匿名内部类
        show(new FunctionalInterface() {
            @Override
            public void method() {
                System.out.println("匿名内部类");
            }
        });

        //方法的参数也是一个函数式接口,所以可以用Lambda。
        show(()-> System.out.println("Lambda"));
    }
}

Lambda作为返回值:

public class Demo {
   public static Comparator<String> getComparator(){
      return ((o1, o2) -> o2.length()-o1.length());
   }

    public static void main(String[] args) {
        String[] arr={"aa","bbb","cccc"};
        Arrays.sort(arr,getComparator());
        System.out.println(Arrays.toString(arr));
    }
}

 Stream流式思想:

Stream 流的方式,遍历集合,对集合中的数据进行过滤。

Stream流是JDK1.8 之后出现的。

public class Demo {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        list.add("张玉昊");
        list.add("胡云钰");
        list.add("张日天");
        list.add("张天");
        list.stream().filter(name->name.startsWith("张"))
                      .filter(name->name.length()==3)
                      .forEach(name-> System.out.println(name));
    }
}

获取Stream流:

java.util.stream.Stream<T> ,是Java8 加入的最常用的流接口。

1、所有的Collection集合都有stream方法来获取流  default Stream<E> stream()

2、Stream接口的静态方法of可以获取数组对应的流。 static <T> Stream<T> of (T...values)

Stream流的常用方法:

forEach:

  forEach用来遍历流中的数据,是一个终结方法,遍历之后就不能再使用Stream其他方法

filter:

  filter用来对Stream流中的数据进行过滤,可以用Lambda。

map:

  将流中元素映射到另一个流中,可以将当前T类型的流转换为R类型的流。

    public static void main(String[] args) {
        Stream<String> stream = Stream.of("1", "2", "3");
        Stream<Integer> stream1 = stream.map(number -> Integer.parseInt(number));
        stream1.forEach(number-> System.out.println(number));
    }

count:

  count方法用于统计Stream流中的元素个数,返回Long类型的整数。

  count方法是一个终结方法。

limit:

  limit方法,延迟方法,对流中的元素截取前几个,返回新的流。limit(Long maxsize),

skip:

  跳过前几个元素,返回新的流,skip(long n)

concat:

  concat:把流组合到一起,concat(流1,流2);

Stream流的特点:

Stream流属于管道流,只能被使用一次。

方法引用:

。。。。。。。。。。。。。

猜你喜欢

转载自www.cnblogs.com/zhangyuhao/p/10908628.html