• Java_Stream流式计算


    什么是Stream流

    定义:支持顺序和并行聚合操作的元素序列

    Stream流本身并不储存数据

    Stream流属于管道流,仅可使用一次;二次使用会抛出IllegalStateException: stream has already been operated upon or closed异常

    创建流

    1.stream方法:创建串行流,即单线程

    2.parallelStream方法:创建并行流,即多线程,但线程不安全

    需要注意的是,parallelStream方法的源码注释中提到,该方法返回的不一定是并行流,也就是说任务可能均由调用者线程执行

    1. * @return a possibly parallel {@code Stream} over the elements in this
    2. * collection
    3. * @since 1.8

    parallelStream方法返回并行流示例:

    1. public class Test {
    2. public static void main(String[] args){
    3. List list = Arrays.asList(1, 2, 3, 4, 5);
    4. list.parallelStream().forEach((num) -> {
    5. System.out.println(Thread.currentThread().getName() + " num=" + num);
    6. });
    7. }
    8. }

     

    若想将流中的数据依次输出,可使用forEachOrdered方法:

    常用方法

    1.forEach方法:遍历流中的数据

    注:若直接调用forEach方法,则调用的是Iterable接口中的forEach方法

    1. public class Test {
    2. public static void main(String[] args){
    3. List list = Arrays.asList(1, 2, 3, 4, 5);
    4. list.stream().forEach(System.out::println);
    5. }
    6. }

     

    2.limit方法:返回由前n个数据组成的流

    1. public class Test {
    2. public static void main(String[] args){
    3. List list = Arrays.asList(1, 2, 3, 4, 5);
    4. list.stream().limit(3).forEach(System.out::println);
    5. }
    6. }

    3.filter方法: 返回由符合要求的数据组成的流

    1. public class Test {
    2. public static void main(String[] args){
    3. List list = Arrays.asList(1, 2, 3, 4, 5);
    4. list.stream().filter(num -> num>=3).forEach(System.out::println);
    5. }
    6. }

    4.map方法: 将操作映射到流中的每一个数据上,返回数据被映射后的流

    1. public class Test {
    2. public static void main(String[] args){
    3. List list = Arrays.asList(1, 2, 3, 4, 5);
    4. list.stream().map(num -> num+1).forEach(System.out::println);
    5. }
    6. }

    5.sorted方法:将流中的数据进行排序,返回数据排序后的流

    1. public class Test {
    2. public static void main(String[] args){
    3. List list = Arrays.asList(1, 2, 3, 4, 5);
    4. list.stream().sorted().forEach(System.out::print);
    5. System.out.println();
    6. list.stream().sorted(Integer::compareTo).forEach(System.out::print);
    7. System.out.println();
    8. list.stream().sorted((num1, num2) -> num2 - num1).forEach(System.out::print);
    9. }
    10. }

  • 相关阅读:
    15. 从零开始编写一个类nginx工具, 如果将nginx.conf转成yaml,toml,json会怎么样
    Python房价分析和可视化<anjuke新房>
    「Java开发指南」如何在MyEclipse中使用JPA和Spring管理事务?(二)
    URL because the SSL module is not available
    Google gtest事件机制
    Redis主从复制+哨兵选举机制分析
    AI干货大FUN送!程序员节来AI Show“集市”行乐
    ubuntu下Anaconda安装与使用教程
    工业节碳分论坛精彩回顾 | 第二届始祖数字化可持续发展峰会
    汽车电子时钟硬件设计指南
  • 原文地址:https://blog.csdn.net/Mudrock__/article/details/127046078