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

【Java Stream】基本用法学习

Java Stream

由于在公司写代码时,发现有大量地方可以优化为使用stream流的方式写,且更加简洁,因此学习了一下stream的基础语法。

Java Stream 是 Java 8 引入的用于处理集合数据的函数式 API,提供了一种高效、声明式的数据处理方式。

1、创建流

// 从集合创建
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream1 = list.stream(); // 从数组创建
String[] array = {"a", "b", "c"};
Stream<String> stream2 = Arrays.stream(array);// 直接创建
Stream<String> stream3 = Stream.of("a", "b", "c");
Stream<Integer> stream4 = Stream.iterate(0, n -> n + 1); // 无限流
Stream<Double> stream5 = Stream.generate(Math::random);   // 随机数流// 并行流(Parallel Streams)
list.parallelStream()

2、操作

  • 过滤:filter()
List<String> list = Arrays.asList("a", "b", "c");List<String> filtered = list.stream().filter(s -> s.startsWith("a")) // 过滤以"a"开头的元素.collect(Collectors.toList());  // 结果: ["a"]
  • 映射:map()
List<String> list = Arrays.asList("a", "b", "c");List<Integer> lengths = list.stream().map(String::length) // 将字符串映射为其长度.collect(Collectors.toList()); // 结果: [1, 1, 1]
  • 去重 & 排序:distinct()、sorted()
List<String> result = Stream.of("a", "c", "b", "a").distinct()          // 去重 → ["a", "c", "b"].sorted()            // 排序 → ["a", "b", "c"].collect(Collectors.toList());
  • 截取 & 跳过:skip()、limit()
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> subList = nums.stream().skip(2)   // 跳过前2个 → [3,4,5].limit(2)  // 取前2个   → [3,4].collect(Collectors.toList());
  • 遍历:forEach()
list.stream().forEach(System.out::println); // 输出每个元素
  • 聚合计算:count()、max()
long count = list.stream().count();          // 元素总数
Optional<String> max = list.stream().max(String::compareTo); // 最大值
  • 收集结果
    • 转List/Set:Collectors.toList()、Collectors.toSet()
    • 转Map:Collectors.toMap()
    • 分组:Collectors.groupingBy()
// 转List/Set
List<String> listResult = stream.collect(Collectors.toList());
Set<String> setResult = stream.collect(Collectors.toSet());// 转Map
Map<String, Integer> map = list.stream().collect(Collectors.toMap(s -> s, String::length)); // {a=1, b=1, c=1}// 分组
Map<Integer, List<String>> groupByLength = list.stream().collect(Collectors.groupingBy(String::length)); // 按长度分组
http://www.lryc.cn/news/586642.html

相关文章:

  • vue2入门(1)vue核心语法详解复习笔记
  • 算法学习笔记:18.拉斯维加斯算法 ——从原理到实战,涵盖 LeetCode 与考研 408 例题
  • 一扇门铃,万向感应——用 eventfd 实现零延迟通信
  • 14.使用GoogleNet/Inception网络进行Fashion-Mnist分类
  • 4. 观察者模式
  • Java行为型模式---观察者模式
  • Typecho分类导航栏开发指南:从基础到高级实现
  • 低代码引擎核心技术:OneCode常用动作事件速查手册及注解驱动开发详解
  • Pytorch实现感知器并实现分类动画
  • 深入理解观察者模式:构建松耦合的交互系统
  • 为什么玩游戏用UDP,看网页用TCP?
  • 【C++详解】STL-priority_queue使用与模拟实现,仿函数详解
  • 信息收集实战
  • 【读书笔记】《C++ Software Design》第九章:The Decorator Design Pattern
  • 设计模式:软件开发的高效解决方案(单例、工厂、适配器、代理)
  • 基于无人机 RTK 和 yolov8 的目标定位算法
  • 一文认识并学会c++模板(初阶)
  • AI 助力编程:Cursor Vibe Coding 场景实战演示
  • 基于 Redisson 实现分布式系统下的接口限流
  • 牛客网50题
  • 【C/C++】编译期计算能力概述
  • [Python] -实用技巧篇1-用一行Python代码搞定日常任务
  • python-range函数
  • 校园幸运抽(抽奖系统)测试报告
  • 第七章应用题
  • HT8313功放入门
  • HashMap的原理
  • 数据结构与算法之美:线索二叉树
  • 蒙特卡洛树搜索方法实践
  • 蓝牙调试抓包工具--nRF Connect移动端 使用详细总结