java8新特性

StreamAPI

  • Stream 关注的是对数据的运算,与CPU打交道;集合关注的是数据的存储,与内存打交道
  • Stream 自己不会存储元素。
  • Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。即不可变类型
  • Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
  • Stream 执行流程:
    ①Stream 的实例化
    ②一系列的中间操作(过滤、映射、.…)
    ③终止操作
  • 一个中间操作链,对数据源的数据进行处理;一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
    Stream的实例化
//方式一:集合Collection中有default Stream<E> stream()方法
//       和并行方法:default Stream<E> parallelStream()
//方式二:数组Arrays类中有Stream()方法
//方式三:Stream类中的of()方法
//方式四:创建无限流(待补充)

Stream的中间操作

/**
  1.筛选与切片
     filter(IntPredicate predicate):过滤操作,中间操作
     IntStream limit(long maxSize):限制操作 ,中间操作
 如:Strean<Double> randons = Strean.generate(Math::randon).limit(100);会产生一个包含100个随机数的流。
     void forEach(IntConsumer action):终端操作
*/
    int[] ints = {11, 2, 3,4,5};
    IntStream stream = Arrays.stream(ints);//数组转换为Stream
    stream.filter(value -> value>2).limit(3).forEach(System.out::println); //result:11 3 4

//2.映射-map
/**含义:
 假如有一个员工类:成员变量如 工号,姓名,年龄,工资(double类型)等属性,用
 Stream<Double> salary = employeeList.stream().map(Emeployee::getSalary)可以将工资映射出来,
 返回单独的工资集合
*/
    int[] ints = {11, 2, 3,4,5};
    IntStream stream = Arrays.stream(ints);//数组转换为Stream
    stream.map(a -> a+3).forEach(System.out::println);result:14 5 6 7 8

// 3.排序
public static void test3(){
        List<String> list = Arrays.asList("dd", "cc", "aa");
        //根据String内部compareTo()的排序规则,默认排序
        list.stream().sorted().forEach(System.out::print); // aa cc dd
        System.out.println();
        //Comparator的定制排序
        list.stream().sorted(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return -o1.compareTo(o2);
            }
        }).forEach(System.out::print); //dd cc aa
        //lambda表达式写法
        System.out.println();
        list.stream().sorted((o1,o2) -> -o1.compareTo(o2))
                .forEach(System.out::print); //dd cc aa
   
}

Stream的终止操作

//1. 匹配与查找
public static void test4(){
        int[] ints = {23, 15, 18, 7, 24, 6};
        IntStream stream = Arrays.stream(ints);
        //allMatch:匹配所有元素,若都满足则返回true,反之返回false
        System.out.println(Arrays.stream(ints).allMatch(value -> value > 10));//false
        //anyMatch:匹配任意一个元素,只要有一个满足则返回true,反之返回false
        System.out.println(Arrays.stream(ints).anyMatch(value -> value > 10));//true
        //noneMatch:检查没有匹配的元素,若有匹配返回false
        System.out.println(Arrays.stream(ints).noneMatch(value -> value < 10));//false
        //findFirst:返回第一个元素
        System.out.println(Arrays.stream(ints).findFirst());//OptionalInt[23]
        //count:求个数,返回值long类型
        System.out.println(Arrays.stream(ints).count());//6
        //max,min:求最大最小
        System.out.println(Arrays.stream(ints).max());//OptionalInt[24]
        System.out.println(Arrays.stream(ints).min());//OptionalInt[6]
        //forEach:内部迭代
        Arrays.stream(ints).forEach(System.out::println); //23 15 18 7 24 6  
}
//2.归约
public static void test5(){
        //计算1-5的和
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        //T reduce(T identity, BinaryOperator<T> accumulator);
        //interface BinaryOperator<T> extends BiFunction<T,T,T>
        //int sum(int a, int b) 符合方法引用规则
        System.out.println(list.stream().reduce(0, Integer::sum));//15
   
}
//3.收集
public static void test5(){
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
         //把流中元素收集到List
        List<Integer> integerList = list.stream().collect(Collectors.toList());
        integerList.forEach(System.out::println); //1 2 3 4 5
        System.out.println();
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
         //把流中元素收集到Set
        Set<Integer> integerSet = list1.stream().collect(Collectors.toSet());
        integerSet.forEach(System.out::println); //1 2 3 4 5   
}

Optional

  • 为了在程序中避免出现空指针异常而创建的。
  • 常用的方法:
    ofNullable(T t)
    orELse(T t)
posted @ 2021-02-12 14:01  先生胡  阅读(51)  评论(0编辑  收藏  举报