Java8中的Stream API基本用法总结
另外参考:Java8 中的 Stream API 基本用法总结
1、Stream API 说明
2、Stream 的实例化
3、Stream 的中间操作
3.1、筛选和切片
3.2、映射
3.3、排序
4、Stream 的终止操作
4.1、匹配与查找
4.2、归约
4.3、收集
1、Stream API 说明 <-- 返回目录
Java8 中有两个最为重要的改变。第一个是 Lambda 表达式,另外一个则是 Stream API。
Stream API(java.util.stream) 把真正的函数式编程风格引入到 java 中。这是目前为止对 java 类库最好的补充,因为 Stream API 可以极大提高 java 程序员的生产力,让程序员写出高效率、干净、简洁的代码。
Stream 是 java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用 Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
为什么使用 Stream API?
- 实际开发中,项目中多数数据源都来自于 mysql、oracle 等。但现在数据源可以更多了,有 mongdb、redis 等,而这些 nosql 的数据就需要 java 层面去处理。
- Stream 和 Collection 集合的区别:Collection 是一种静态的内存数据结构,而 Stream 是有关计算的。前者是主要面向内存,存储在内存中,后者主要是面向 CPU,通过 CPU 实现计算。
什么是 Stream?
Stream 的操作三步骤
2、Stream 的实例化 <-- 返回目录
@Test public void test() { // 创建 Stream 方式一: 集合, Collection 的方法 default Stream<E> stream() List<String> list = new ArrayList<>(); list.add("aaa"); Stream<String> stream = list.stream();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 创建Stream方式二: 数组 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> Arrays.stream()接收基本类型数组</span> <span style="color: rgba(0, 0, 255, 1)">int</span>[] arr1 = <span style="color: rgba(0, 0, 255, 1)">new</span> <span style="color: rgba(0, 0, 255, 1)">int</span>[] {1,2,3<span style="color: rgba(0, 0, 0, 1)">}; IntStream inStream </span>=<span style="color: rgba(0, 0, 0, 1)"> Arrays.stream(arr1); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> Arrays.stream()接收非基本类型数组</span> Integer[] arr2 = <span style="color: rgba(0, 0, 255, 1)">new</span> Integer[] {1,2,3<span style="color: rgba(0, 0, 0, 1)">}; Stream</span><Integer> stream2 =<span style="color: rgba(0, 0, 0, 1)"> Arrays.stream(arr2); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 创建Stream方式三: Stream.of()</span> Stream<Integer> stream3 = Stream.of(1,2,3<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 无限流: 迭代 </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 遍历前10个偶数</span> Stream.iterate(0, t -> t + 2).limit(10<span style="color: rgba(0, 0, 0, 1)">).forEach(System.out::println); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 无限流: 生成</span> Stream.generate(Math::random).limit(10<span style="color: rgba(0, 0, 0, 1)">).forEach(System.out::println);
}
3、Stream 的中间操作 <-- 返回目录
3.1、筛选和切片 <-- 返回目录
3.2、映射 <-- 返回目录
3.3、排序 <-- 返回目录
4、Stream 的终止操作 <-- 返回目录
4.1、匹配与查找 <-- 返回目录
4.2、归约 <-- 返回目录
@Test public void test() { // 数组求和 List<Integer> list = Arrays.asList(1,2,3,4,5); int sum = list.stream().reduce(0, Integer::sum); System.out.println(sum); }
4.3、收集 <-- 返回目录
---