Stream方法

Stream主要有以下几种方法:

    遍历/匹配(foreach/find/match)筛选(filter)聚合(max/min/count)映射(map/flatMap)归约(reduce)

遍历/匹配(foreach/find/match)

Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常简单。

     List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);// 遍历输出符合条件的元素list.stream().filter(x -> x > 6).forEach(System.out::println);// 匹配第一个Optional<Integer> first = list.stream().filter(x -> x > 5).findFirst();System.out.println("匹配第一个:" + first);// 匹配任意(适用于并行流)Optional<Integer> any = list.parallelStream().filter(x -> x > 6).findAny();System.out.println("匹配任意:" + any);// 是否包含符合特定条件的元素boolean anyMatch = list.stream().anyMatch(x -> x < 6);System.out.println("是否存在小于6的值:" + anyMatch);

筛选(filter)

筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作。

        /*** 例子1:筛选出Integer集合中大于7的元素,并打印出来*/List<Integer> list1 = Arrays.asList(6, 7, 3, 8, 1, 2, 9);Stream<Integer> stream = list1.stream();stream.filter(x -> x > 7).forEach(System.out::println);/*** 例子2:筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集)*/List<Person> personList = new ArrayList<Person>();personList.add(new Person("Tom", 8900, 22, "male", "New Yark"));personList.add(new Person("Jack", 7000, 23, "male", "Washington"));personList.add(new Person("Lily", 7800, 24, "female", "Washington"));personList.add(new Person("Anni", 8200, 25, "female", "New Yark"));personList.add(new Person("Owen", 9500, 26, "male", "New Yark"));personList.add(new Person("Alisa", 7900, 27, "female", "New Yark"));List<String> fiterList =personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName).collect(Collectors.toList());System.out.println("高于8000的员工姓名:" + fiterList);

聚合(max/min/count)

max、min、count这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。

         /*** 案例一:获取String集合中最长的元素。*/List<String> list3 = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");Optional<String> maxString = list3.stream().max(Comparator.comparing(String::length));System.out.println("集合中字符串长度最长的元素是:" + maxString.get());/*** 案例二:获取Integer集合中的最大值。*///自然排序Optional<Integer> maxValue = list.stream().max(Integer::compareTo);System.out.println("自然排序----集合中值最大的元素是:" + maxValue.get());//自定义排序Optional<Integer> max = list.stream().max(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o1.compareTo(o2);}});System.out.println("自定义排序---集合中最大的元素是:" + max.get());/*** 案例三:获取员工工资最高的人。*/Optional<Person> person = personList.stream().max(Comparator.comparingInt(Person::getSalary));System.out.println("员工工资最大值是:"+person.get().getSalary());/*** 案例四:计算Integer集合中大于6的元素的个数。*/long count = list.stream().filter(x->x>6).count();System.out.println("集合中大于6的元素的个数:"+count);

映射(map/flatMap)

映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap:

map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
         /*** 案例一:英文字符串数组的元素全部改为大写。整数数组每个元素+3。*/String[] strArr = { "abcd", "bcdd", "defde", "fTr" };List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());System.out.println("变成大写后的元素:"+strList);List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);System.out.println("整数数组每个元素+3:"+intList.stream().map(x->x+3).collect(Collectors.toList()));/*** 案例二:将员工的薪资全部增加1000*/
//        List<Integer> salary = personList.stream().map(x->x.getSalary()+1000).collect(Collectors.toList());
//        System.out.println("员工的工资+1000之后的值是:"+salary);// 不改变原来员工集合的方式List<Person> personListNew = personList.stream().map(person1->{Person personNew = new Person(person1.getName(), 0, 0, null, null);personNew.setSalary(person1.getSalary()+1000);return personNew;}).collect(Collectors.toList());System.out.println("一次改动前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary());System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());// 改变原来员工集合的方式List<Person> personListNew2 = personList.stream().map(person2 -> {person2.setSalary(person2.getSalary() + 10000);return person2;}).collect(Collectors.toList());System.out.println("二次改动前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary());System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary());/*** 案例三:将两个字符数组合并成一个新的字符数组。*/List<String> list4 = Arrays.asList("m,k,l,a", "1,3,5,7");List<String> listNew = list4.stream().flatMap(s -> {// 将每个元素转换成一个streamString[] split = s.split(",");Stream<String> s2 = Arrays.stream(split);return s2;}).collect(Collectors.toList());System.out.println("处理前的集合:" + list4);System.out.println("处理后的集合:" + listNew);

归约(reduce)

归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。

         /*** 案例一:求Integer集合的元素之和、乘积和最大值。*/List<Integer> list5 = Arrays.asList(1, 3, 2, 8, 11, 4);// 求和方式1Optional<Integer> sum = list5.stream().reduce((x, y) -> x + y);// 求和方式2Optional<Integer> sum2 = list5.stream().reduce(Integer::sum);// 求和方式3Integer sum3 = list5.stream().reduce(0, Integer::sum);// 求乘积Optional<Integer> product = list5.stream().reduce((x, y) -> x * y);// 求最大值方式1Optional<Integer> max1 = list5.stream().reduce((x, y) -> x > y ? x : y);// 求最大值写法2Integer max2 = list5.stream().reduce(1, Integer::max);System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);System.out.println("list求积:" + product.get());System.out.println("list求和:" + max1.get() + "," + max2);/*** 案例二:求所有员工的工资之和和最高工资。*/// 求和方式1Integer sumSalary = personList.stream().reduce(0,(sum1, p)->sum1 += p.getSalary(),(sum4 ,sum5)-> sum4 + sum5);System.out.println("求和方式一---所有员工工资之和:"+sumSalary);// 求和方式2Optional<Integer> sumSalary2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);System.out.println("求和方式二---所有员工工资之和:"+sumSalary2.get());// 求和方式3Integer sumSalary3 = personList.stream().reduce(0,(sum1, p) -> sum1 += p.getSalary(), Integer::sum);System.out.println("求和方式三---所有员工工资之和:"+sumSalary3);// 求最高工资方式1:Integer maxSalary = personList.stream().reduce(0, (max3, p) -> max3 > p.getSalary()? max3 :p.getSalary(),Integer::max);System.out.println("最大值方式一---员工的最高工资:"+maxSalary);// 求最高工资方式2:Integer maxSalary2 = personList.stream().reduce(0, (max3, p) -> max3 > p.getSalary()? max3 :p.getSalary(),(max4 ,max5)-> max4 > max5 ? max4 : max5);System.out.println("最大值方式二---员工的最高工资:"+maxSalary2);}

Java8新特性之Stream--Stream方法相关推荐

  1. Java8新特性总结 -5.Stream API函数式操作流元素集合

    所有示例代码打包下载 : 点击打开链接 Java8新特性 : 接口新增默认方法和静态方法 Optional类 Lambda表达式 方法引用 Stream API - 函数式操作流元素集合 Date/T ...

  2. Java8新特性 Lambda、Stream、Optional实现原理

    Java8新特性 Lambda.Stream.Optional实现原理 一.接口中默认方法修饰为普通方法 二.Lambda表达式 2.1.什么是Lambda表达式 2.2.为什么要使用Lambda表达 ...

  3. JAVA8 新特性-Lamda跟Stream

    JAVA8 新特性-Lamda跟Stream 主要内容 Lambda 表达式 函数式接口 方法引用与构造器引用 Stream API 接口中的默认方法与静态方法 新时间日期 API 其他新特性 Jav ...

  4. java8新特性(2)--- 方法引用

    java8新特性(2)- 方法引用 新增语法双冒号(::) package com.common.jdk8;import java.util.Arrays; import java.util.List ...

  5. 零基础学习java------21---------动态代理,java8新特性(lambda, stream,DateApi)

    1. 动态代理 在一个方法前后加内容,最简单直观的方法就是直接在代码上加内容(如数据库中的事务),但这样写不够灵活,并且代码可维护性差,所以就需要引入动态代理 1.1 静态代理实现 在讲动态代理之前, ...

  6. 【Java8新特性】浅谈方法引用和构造器引用

    写在前面 Java8中一个很牛逼的新特性就是方法引用和构造器引用,为什么说它很牛逼呢?往下看! 方法引用 当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!这里需要注意的是:实现抽 ...

  7. java8新特性Lambda和Stream以及函数式接口等新特性介绍

    主要内容 1.Lambda 表达式 2.函数式接口 3.方法引用与构造器引用 4.Stream API 5.接口中的默认方法与静态方法 6.新时间日期API 7.其他新特性 Java 8新特性简介 速 ...

  8. Java8新特性之三:Stream API

    Java8的两个重大改变,一个是Lambda表达式,另一个就是本节要讲的Stream API表达式.Stream 是Java8中处理集合的关键抽象概念,它可以对集合进行非常复杂的查找.过滤.筛选等操作 ...

  9. JAVA8新特性Optional和Stream和Localdate用法

    1.Optional类是Java8为了解决null值判断问题 2.Stream 是Java SE 8类库中新增的关键抽象,Java 8 引入的的Stream主要用于取代部分Collection的操作, ...

  10. Java8新特性:使用Stream流递归实现遍历树形结构

    作者:Lcry blog.csdn.net/qq_19244927/article/details/106481777 可能平常会遇到一些需求,比如构建菜单,构建树形结构,数据库一般就使用父id来表示 ...

最新文章

  1. iOS隐藏键盘的几种方式
  2. 一些图形学中的数学应用
  3. 将社交登录添加到Spring MVC Web应用程序:配置
  4. 【RS码1】系统RS码编码原理及MATLAB实现(不使用MATLAB库函数)
  5. webpack2入门概念
  6. 我是如何开发一个项目的
  7. 2017.3.6~2017.3.7 Harry And Magic Box 思考记录(特别不容易)
  8. 更适合智能家庭使用的新 Wi-Fi 技术问世了
  9. php多级审核,BOS单据多级审核需在单据头上列示多个审核人员的处理方法
  10. C# AHP层次分析法:一致性校验
  11. 微信 PC(电脑端) 多开批处理
  12. 【产品】禅道项目管理核心思想
  13. win 10 如何删除需要获取管理员权限的文件和退出安全模式
  14. 度娘果然毫无节操,纯粹就是order by 广告费 desc
  15. Ubuntu21.10配置阿里云DNS
  16. GoldenGate添加进程及初始化
  17. Python倒叙的几种方法
  18. 【PyTorch】3 AI诗人RNN实战(LSTM)——完成诗歌剩余部分、生成藏头诗
  19. 统计学习(三):分类
  20. Python爬虫入门 | 4 爬取豆瓣TOP250图书信息

热门文章

  1. AutoML在计算机视觉领域的能与不能
  2. selenium webdriver 实现浏览器窗口自动下滑至底端
  3. MySQL insert value与values
  4. 项目九 配置磁盘配额与管理RAID卷
  5. Linux运维实战:Centos逻辑卷磁盘挂载流程
  6. jsp连接mysql数据库,实现含验证码的用户登录
  7. chirp-RNA与蛋白/DNA互作实验技术
  8. 基于Java的网络兼职平台系统的设计与实现(论文+程序设计+数据库文件)
  9. 在cocos2dx中实现水波滤镜
  10. #实现拖拉文件_硬核测评7款主流农用拖拉机:“小鹿”?甩了对手N条街