java8新特性:StreamAPI

StreamAPI到底是什么?

集合讲的是数据,流讲的是计算。

注意:

1stream自己不会存储元素。

2stream不会改变源对象,相反,他会返回一个新的stream。

3stream操作是延迟执行的,这意味着我们要等到需要结果的时候才执行。

Stream操作分三个步骤

1创建Stream

2中间操作

3终止操作

一、创建Stream

 @Test
    public void test1(){
        //1通过Collection系列集合提供的stream()或 paralleStream()
        List<String> list = new ArrayList<String>();
        Stream<String> stream1 = list.stream();
        Stream<String> stringStream = list.parallelStream();

        //2通过 Arrays中的静态方法stream()
        Student[] studentArray = new Student[10];
        Stream<Student> stream2 = Arrays.stream(studentArray);

        //3通过Stream类的静态方法of()
        Stream<String> stream3 = Stream.of("a", "b");

        //4无限流
        //迭代
        Stream<Integer> stream4 = Stream.iterate(2, (x) -> x +2);
        stream4.limit(5).forEach(System.out::println);

        //生成
        Stream<Double> stream5 = Stream.generate(() -> Math.random());
        stream5.limit(5).forEach(System.out::println);

    }

二、中间操作

1筛选和切片

     filter 接收lambda,从流中排除某些元素
     limit 截断流,使其元素不穿过给定数量
     skip(n) 跳过元素,返回一个丢掉前n个元素的流,若流不足n个,返回一个空流,与limit互补

     distinct 去重,通过元素的hashCode() 和 equals()比较去重


filter

 /**
     * filter
     * 内部迭代:迭代操作由StreamAPI完成
     */
    @Test
    public void test1(){
        //中间操作 不会执行任何操作
        Stream<Student> stream = studentList.stream()
                .filter((e) -> {
                    System.out.println("中间操作");
                    return e.getAge() > 13;
                });
        System.out.println("-----------------------------------------");
        //终止操作 一次性执行全部内容,即“惰性求值”
        stream.forEach(System.out::println);
    }

 //外部迭代
    @Test
    public void test2(){
        Iterator<Student> iterator = studentList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

limit

/**
     * 截断流 一旦找到满足条件的数据,后续的迭代结束
     */
    @Test
    public void test3(){
        studentList.stream()
                .filter((e)->{
                    System.out.println("短路!");
                    return e.getScore()>60;
                })
                .limit(2)
                .forEach(System.out::println);
    }

skip

   /**
     * 跳过
     */
    @Test
    public void test4(){
        studentList.stream()
                .filter(e->e.getScore()>60)
                .skip(2)
                .forEach(System.out::println);
    }

distinct

 /**
     * 去重
     */
    @Test
    public void test5(){
        studentList.stream()
                .distinct()
                .forEach(System.out::println);
    }

2映射

   map 接收lambda 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成为一个新的元素
   flatMap 接收一个函数为参数,将流中的每个值换成另一个流,然后把所有的流连接成一个流

 @Test
    public void test6(){
        List<String> list = Arrays.asList("aaa","bbb","ccc");
        list.stream()
                .map((e)->e.toUpperCase())
                .forEach(System.out::println);

        System.out.println("--------------------");

        studentList.stream()
                .map(e->e.getName())
                .forEach(System.out::println);

        System.out.println("----------------------");

        Stream<Stream<Character>> streamStream = list.stream()
                .map(TestStreamAPI2::filterCharcater);
        streamStream.forEach((e)->e.forEach(System.out::print));

        System.out.println("------------------");
        list.stream()
                .flatMap(TestStreamAPI2::filterCharcater)
                .forEach(System.out::print);

    }

3排序

   sorted() 自然排序
   sorted(Compator com) 定制排序

  @Test
    public void test7(){
        List<String> list = Arrays.asList("cc","a","df","ab","ca");
        list.stream()
                .sorted()
                .forEach(System.out::println);
        System.out.println("---------------------------");
        studentList.stream()
                .sorted((e1,e2)->{
                    if(e1.getAge()==e1.getAge()){
                        return e1.getName().compareTo(e2.getName());
                    }else{
                        return Integer.compare(e1.getAge(),e2.getAge());
                    }
                })
                .forEach(System.out::println);
    }

三、终止操作

  List<Student> studentList =null;
    @Before
    public void befor(){
        studentList = Arrays.asList(
                new Student("zhangsan",15,93, Student.Status.BUSY),
                new Student("lisi",16,100, Student.Status.FREE),
                new Student("wangwu",17,86, Student.Status.VOCATION),
                new Student("zhaoliu",13,71, Student.Status.FREE),
                new Student("yuanqi",13,65, Student.Status.FREE)
        );
    }

1匹配

    /**
     * 查找与匹配
     * allMatch 检查是否匹配所有元素
     * anyMacth 检查是否至少匹配一个元素
     * noneMacth 检查是否没有匹配所有元素
     * findFirst 返回第一个元素
     * findAny 返回任意一个元素
     * count 返回元素总数
     * max 返回最大值
     * min 返回最小值

     */

    @Test
    public void test1(){
        boolean b1 = studentList.stream()
                .allMatch((e) -> e.getStatus() == Student.Status.FREE);
        System.out.println(b1);

        boolean b2 = studentList.stream()
                .anyMatch((e) -> e.getStatus() == Student.Status.FREE);
        System.out.println(b2);

        boolean b3 = studentList.stream()
                .noneMatch((e) -> e.getStatus() == Student.Status.FREE);
        System.out.println(b3);

        Optional<Student> op1 = studentList.stream()
                .sorted((e1, e2) -> -Integer.compare(e1.getScore(), e2.getScore()))
                .findFirst();
        System.out.println(op1.get());

        Optional<Student> op2 = studentList.stream()
                .filter((e) -> e.getStatus() == Student.Status.FREE)
                .findAny();
        System.out.println(op2.get());
        //并行流
        Optional<Student> op3 = studentList.parallelStream()
                .filter((e) -> e.getStatus() == Student.Status.FREE)
                .findAny();
        System.out.println(op3.get());
        //count
        long count = studentList.stream()
                .count();
        System.out.println(count);
        //max
        Optional<Student> max = studentList.stream()
                .max(Comparator.comparing(Student::getName));
        System.out.println(max.get());
        //min
        Optional<Integer> min = studentList.stream()
                .map(e -> e.getScore())
                .min(Integer::compare);
        System.out.println(min.get());

    }

2归约

reduce(T identity,BinaryOperator) /reduce(BinaryOperator) 将流中元素反复结合起来 得到一个值

    @Test
    public void test2(){
        List<Integer> lsit = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer sum = lsit.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        System.out.println("--------------");

        Integer sum2 = studentList.stream()
                .map(Student::getScore)
                .reduce(0, (x, y) -> x + y);
        System.out.println("分数总和"+sum2);

    }

3收集

collect 将流转换为其他形式,接收一个Collector接口的实现,用于将Stream重点额元素做汇总的方法

 @Test
    public void test3(){
        List<String> collect = studentList.stream()
                .map(Student::getName)
                .collect(Collectors.toList());
        System.out.println(collect);
        System.out.println("----------------");
        Set<String> collect1 = studentList.stream()
                .map(Student::getName)
                .collect(Collectors.toSet());
        System.out.println(collect1);
        System.out.println("------------");
        HashSet<String> collect2 = studentList.stream()
                .map(Student::getName)
                .collect(Collectors.toCollection(HashSet::new));
    }
    @Test
    public void test4(){
        //总数
        Long count = studentList.stream()
                .collect(Collectors.counting());
        System.out.println(count);
        System.out.println("-------------");
        //平均数
        Double avg = studentList.stream()
                .collect(Collectors.averagingInt(Student::getScore));
        System.out.println(avg);
        System.out.println("-----------------");
        //总和
        Integer sum = studentList.stream()
                .collect(Collectors.summingInt(Student::getScore));
        System.out.println(sum);
        System.out.println("-----------------");

        //最大值
        Optional<Student> max = studentList.stream()
                .collect(Collectors.maxBy((e1, e2) -> Integer.compare(e1.getScore(), e2.getScore())));
        System.out.println(max.get());
        System.out.println("------------");
        //最小值

        Optional<Integer> min = studentList.stream()
                .map(Student::getScore)
                .collect(Collectors.minBy(Integer::compare));
        System.out.println(min);
        System.out.println("-----------------");
    }

4分组

 /**
     * 分组
     */
    @Test
    public void test5(){
        Map<Student.Status, List<Student>> map = studentList.stream()
                .collect(Collectors.groupingBy(Student::getStatus));
        System.out.println(map);
    }
    @Test
    public void test6(){
        Map<Student.Status, Map<String, List<Student>>> map = studentList.stream()
                .collect(Collectors.groupingBy(Student::getStatus, Collectors.groupingBy((e) -> {
                    if (e.getAge() < 15) {
                        return "小朋友";
                    } else {
                        return "青年";
                    }
                })));
        System.out.println(map);
    }

5分区

 @Test
    public void test7(){
        Map<Boolean, List<Student>> map = studentList.stream()
                .collect(Collectors.partitioningBy((e) -> e.getScore() > 70));
        System.out.println(map);
    }

6统计

   @Test
    public void test8(){
        IntSummaryStatistics iss = studentList.stream()
                .collect(Collectors.summarizingInt(Student::getScore));
        System.out.println(iss.getSum());
        System.out.println(iss.getAverage());
        System.out.println(iss.getCount());
        System.out.println(iss.getMax());
    }

7拼接

    @Test
    public void test9(){
        String str = studentList.stream()
                .map(Student::getName)
                .collect(Collectors.joining(","));
        System.out.println(str);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值