当前位置: 首页 > article >正文

Stream流学习

Stream流

把数据放进stream流水线,对数据进行一系列操作(中间方法),最后封装(终结方法)。

Stream.of()允许传入任何参数

  • 常见中间方法

    可以对数据进行链式(流水线)操作,但中间方法返回的都是stream对象

    Stream.of(1, 2, 3, 4, 5)
         .filter(n -> n % 2 == 0) // 只保留偶数
         .forEach(System.out::println);//打印
    
    
    Stream.of("a", "b", "c")
         .map(String::toUpperCase) // 将每个字符串转换为大写
         .forEach(System.out::println);
    
    
    Stream.of(1, 2, 2, 3, 4, 4)
         .distinct()
         .forEach(System.out::println); // 输出 1, 2, 3, 4
    
    
    Stream.of(5, 3, 1, 4, 2)
         .sorted() // 默认升序排序
         .forEach(System.out::println);
    
    
    Stream.of(1, 2, 3, 4, 5)
         .limit(3) // 只保留前 3 个元素
         .forEach(System.out::println);
    
    
    Stream.of(1, 2, 3, 4, 5)
         .skip(2) // 跳过前 2 个元素
         .forEach(System.out::println); // 输出 3, 4, 5
    
    
    
    
    
    Stream().map()//将流中的每一个数据转化为另一种形式,并返回新流
    //1数据转化
    List<String> strings = Arrays.asList("apple", "banana", "cherry");
    List<String> upperCaseStrings = strings.stream()
        .map(String::toUpperCase)//转化为大写
        .collect(Collectors.toList());
    System.out.println("Upper Case Strings: " + upperCaseStrings);
    
    Upper Case Strings: [APPLE, BANANA, CHERRY]
    
    //2数据处理
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    List<Integer> squaredNumbers = numbers.stream()
        .map(n -> n * n)//获得平方
        .collect(Collectors.toList());
    System.out.println("Squared Numbers: " + squaredNumbers);
    
    Squared Numbers: [1, 4, 9, 16, 25]
    
    
    //3复杂对象转化
    class User {
        String name;
        int age;
    
        User(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    }
    
    List<User> users = Arrays.asList(
        new User("Alice", 23),
        new User("Bob", 17),
        new User("Charlie", 25)
    );
    
    List<String> userNames = users.stream()
        .map(User::getName)//获得对象里的名字
        .collect(Collectors.toList());//并以list返回
    System.out.println("User Names: " + userNames);
    
    User Names: [Alice, Bob, Charlie]
    
    
  • 常见终结方法

    终结方法会结束流的操作,并返回一个结果,如基本类型(double,string等),或对象(List,map等),特殊值(void等)

    Stream.of("a", "b", "c").forEach(System.out::println);
    
    
    List<String> list = Stream.of("a", "b", "c").collect(Collectors.toList());
    
    
    
    Stream().reduce()
    int sum = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
    reduce 方法允许我们将流中的元素组通过操作(求和、求积、连接字符串等)合成一个单一的结果。它接收两个参数:
    初始值(identity):归约操作的初始值,如果流为空,则返回该值。
    累加器(accumulator):用于将流中的元素累积到一个结果中的函数。
    求和为例:
    public class ReduceExamples {
    
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    
            // 使用 reduce 求和
            int sum = numbers.stream()
                             .reduce(0, (a, b) -> a + b);//0为初始值,如果流中没有数据返回的值
            											//(a, b) -> a + b是将前一个累积值a加上当前流上的数据b
    
            System.out.println("Sum of numbers: " + sum); 
            // 输出:Sum of numbers: 15
        }
    }
    
    复杂对象(苍穹外卖)为例:
    //计算规定天数内的所有订单总量
    Integer allOrder = orderList.stream().reduce(Integer::sum).get();//其中orderList是每天的订单总量,这里将每天订单量求和了。
    
    //如果集合里存的是对象,若想获得对象里的其中值和:
    public class ReduceExamples {
    
        public static void main(String[] args) {
            List<Product> products = Arrays.asList(
                    new Product("iPhone", 999.99),
                    new Product("Laptop", 1499.99),
                    new Product("Headphones", 199.99)
            );
    
            // 使用 reduce 求产品价格总和
            double totalPrice = products.stream()
                                       .mapToDouble(Product::getPrice)//通过 mapToDouble 将 Product 对象映射为其价格
                                       .reduce(0, Double::sum);
    
            System.out.println("Total price of products: " + totalPrice); 
            // 输出:Total price of products: 2699.97
        }
    }
    
    
    
    
    
    long count = Stream.of("a", "b", "c").count();//数据数量
    
    
    boolean hasA = Stream.of("a", "b", "c").anyMatch(s -> s.equals("a"));//数据中是否有满足的
    
    
    boolean allMatch = Stream.of(1, 2, 3).allMatch(n -> n < 5);//数据是否全部满足
    
    
    Optional<String> first = Stream.of("a", "b", "c").findFirst();//数据如果有,返回第一个
    
    

http://www.kler.cn/a/580358.html

相关文章:

  • 【基于C#实现Bartender多条码打印的示例】
  • 比特币中的相关技术
  • 数据结构(蓝桥杯常考点)
  • 【测试框架篇】单元测试框架pytest(4):assert断言详解
  • 使用Beanshell前置处理器对Jmeter的请求body进行加密
  • uniapp简单table表
  • clickhouse可视化分析工具
  • el-pagination的使用说明
  • 基于STC89C52的4x4矩阵键盘对应键值显示测试
  • 基于Spring Boot的社区老人健康信息管理系统设计与实现(LW+源码+讲解)
  • LiveCommunicationKit OC 实现
  • P10周:Pytorch实现车牌识别
  • 华为eNSP:实验 配置P2P网络类型
  • 批量删除多个 Excel 文件中的宏
  • 命名管道的创建和通信实现
  • stm32 f4 flash 调用时卡死
  • LeetCode 404. 左叶子之和 java题解
  • Git和GitHub基础教学
  • Netty入门教程
  • 【软考-架构】11.1、面向对象基本概念-分析设计测试