Java Stream中的API你都用过了吗?

公众号「架构成长指南」,专注于生产实践、云原生、分布式系统、大数据技术分享。

在本教程中,您将通过大量示例来学习 Java 8 Stream API。

Java 在 Java 8 中提供了一个新的附加包,称为 java.util.stream。该包由类、接口和枚举组成,允许对元素进行函数式操作。 您可以通过在程序中导入 java.util.stream包来使用流。

Stream提供以下功能:

Stream不存储元素。它只是通过计算操作的管道传送来自数据结构、数组或 I/O 通道等源的元素。

Stream本质上是函数式的,对流执行的操作不会修改其源。例如,过滤从集合获取的 Stream 会生成一个没有过滤元素的新 Stream,而不是从源集合中删除元素。

Stream是惰性的,仅在需要时才计算代码,在流的生命周期中,流的元素仅被访问一次。

与迭代器一样,必须生成新流才能重新访问源中的相同元素。
您可以使用 Stream 来 过滤、收集、打印以及 从一种数据结构转换为其他数据结构等。

Stream API 示例

1. 创建一个空的Stream

在创建空流时,应使用 empty() 方法:

Stream<String> stream = Stream.empty();
stream.forEach(System.out::println);

通常情况下,在创建时会使用 empty() 方法,以避免在没有元素的流中返回 null:

public Stream<String> streamOf(List<String> list) {return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}
2.从集合中创建流
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;public class StreamCreationExamples {public static void main(String[] args) throws IOException {Collection<String> collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");Stream<String> stream2 = collection.stream();stream2.forEach(System.out::println);List<String> list = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");Stream<String> stream3 = list.stream();stream3.forEach(System.out::println);Set<String> set = new HashSet<>(list);Stream<String> stream4 = set.stream();stream4.forEach(System.out::println);}
}

输出

JAVA
J2EE
Spring
Hibernate
JAVA
J2EE
Spring
Hibernate
JAVA
Hibernate
J2EE
Spring
3. 从数组中创建流对象

数组可以是流的源,也可以从现有数组或数组的一部分创建数组:

import java.util.Arrays;
import java.util.stream.Stream;public class StreamCreationExample {public static void main(String[] args) {// 使用Arrays.stream()创建流int[] numbers = {1, 2, 3, 4, 5};Stream<Integer> stream1 = Arrays.stream(numbers);System.out.println("Using Arrays.stream():");stream1.forEach(System.out::println);// 使用Stream.of()创建流String[] names = {"Alice", "Bob", "Charlie"};Stream<String> stream2 = Stream.of(names);System.out.println("Using Stream.of():");stream2.forEach(System.out::println);// 使用Stream.builder()创建流String[] colors = {"Red", "Green", "Blue"};Stream.Builder<String> builder = Stream.builder();for (String color : colors) {builder.add(color);}Stream<String> stream3 = builder.build();System.out.println("Using Stream.builder():");stream3.forEach(System.out::println);}
}

输出

Using Arrays.stream():
1
2
3
4
5
Using Stream.of():
Alice
Bob
Charlie
Using Stream.builder():
Red
Green
Blue
4. 使用Stream过滤一个集合示例

在下面的示例中,我们不使用流过滤数据,看看代码是什么样的,同时我们在给出一个使用stream过滤的示例,对比一下

不使用Stream过滤一个集合示例

import java.util.ArrayList;
import java.util.List;public class FilterWithoutStreamExample {public static void main(String[] args) {List<Integer> numbers = new ArrayList<>();numbers.add(10);numbers.add(20);numbers.add(30);numbers.add(40);numbers.add(50);List<Integer> filteredNumbers = new ArrayList<>();for (Integer number : numbers) {if (number > 30) {filteredNumbers.add(number);}}System.out.println("Filtered numbers (without Stream):");for (Integer number : filteredNumbers) {System.out.println(number);}}
}

输出:

Filtered numbers (without Stream):
40
50

使用 Stream 过滤集合示例:

import java.util.ArrayList;
import java.util.List;public class FilterWithStreamExample {public static void main(String[] args) {List<Integer> numbers = new ArrayList<>();numbers.add(10);numbers.add(20);numbers.add(30);numbers.add(40);numbers.add(50);List<Integer> filteredNumbers = numbers.stream().filter(number -> number > 30).toList();System.out.println("Filtered numbers (with Stream):");filteredNumbers.forEach(System.out::println);}
}

输出:

Filtered numbers (with Stream):
40
50

前后我们对比一下,可以看到,使用 Stream 进行集合过滤可以更加简洁和直观,减少了手动迭代和添加元素的步骤。它提供了一种声明式的编程风格,使代码更易读、可维护和可扩展。

5. 使用Stream过滤和遍历集合

在下面的示例中,我们使用 filter() 方法进行过滤,使用 forEach() 方法对数据流进行迭代:

import java.util.ArrayList;
import java.util.List;public class FilterAndIterateWithStreamExample {public static void main(String[] args) {List<String> names = new ArrayList<>();names.add("Alice");names.add("Bob");names.add("Charlie");names.add("David");names.add("Eve");System.out.println("Filtered names starting with 'A':");names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);}
}

输出

Filtered names starting with 'A':
Alice

在上述示例中,我们有一个字符串列表 names,其中包含了一些名字。
我们使用 Stream 进行过滤和迭代操作以查找以字母 “A” 开头的名字。

6.使用Collectors方法求和

我们还可以使用Collectors计算数值之和。

在下面的示例中,我们使用Collectors类及其指定方法计算所有产品价格的总和。

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class SumByUsingCollectorsMethods {public static void main(String[] args) {List < Product > productsList = new ArrayList < Product > ();productsList.add(new Product(1, "HP Laptop", 25000f));productsList.add(new Product(2, "Dell Laptop", 30000f));productsList.add(new Product(3, "Lenevo Laptop", 28000f));productsList.add(new Product(4, "Sony Laptop", 28000f));productsList.add(new Product(5, "Apple Laptop", 90000f));double totalPrice3 = productsList.stream().collect(Collectors.summingDouble(product -> product.getPrice()));System.out.println(totalPrice3);}
}

输出

201000.0
7. 使用Stream查找年龄最大和最小的学生

假设有一个 Student 类具有 name 和 age 属性。我们可以使用 Stream 来查找学生集合中年龄的最大和最小值,并打印出相应的学生信息。以下是一个示例:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;public class StudentStreamExample {public static void main(String[] args) {List<Student> students = new ArrayList<>();students.add(new Student("Alice", 20));students.add(new Student("Bob", 22));students.add(new Student("Charlie", 19));students.add(new Student("David", 21));// 查找年龄最大的学生Optional<Student> maxAgeStudent = students.stream().max(Comparator.comparingInt(Student::getAge));// 查找年龄最小的学生Optional<Student> minAgeStudent = students.stream().min(Comparator.comparingInt(Student::getAge));// 打印最大和最小年龄的学生信息System.out.println("Student with maximum age:");maxAgeStudent.ifPresent(System.out::println);System.out.println("Student with minimum age:");minAgeStudent.ifPresent(System.out::println);}
}class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
}

输出:

Student with maximum age:
Student{name='Bob', age=22}
Student with minimum age:
Student{name='Charlie', age=19}
8. 使用Stream转换List为Map
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;public class StudentStreamToMapExample {public static void main(String[] args) {List<Student> students = new ArrayList<>();students.add(new Student("Alice", 20));students.add(new Student("Bob", 22));students.add(new Student("Charlie", 19));students.add(new Student("David", 21));// 将学生列表转换为 Map,以姓名为键,学生对象为值Map<String, Student> studentMap = students.stream().collect(Collectors.toMap(Student::getName, student -> student));// 打印学生 Mapfor (Map.Entry<String, Student> entry : studentMap.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}}
}class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
}

输出

David: Student{name='David', age=21}
Bob: Student{name='Bob', age=22}
Charlie: Student{name='Charlie', age=19}
Alice: Student{name='Alice', age=20}

在上面示例中,我们使用Collectors.toMap() 方法将学生列表转换为 Map。我们指定了键提取器 Student::getName,将学生的姓名作为键。对于值提取器,我们使用了一个匿名函数 student -> student,它返回学生对象本身作为值。

9. 使用Stream把List对象转换为另一个List对象

假设我们有一个 Person 类,其中包含姓名和年龄属性。我们可以使用 Stream 来将一个 List 对象转换为另一个 List 对象,其中只包含人员的姓名。以下是一个示例:

  import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class ListTransformationExample {public static void main(String[] args) {List<Person> persons = new ArrayList<>();persons.add(new Person("Alice", 20));persons.add(new Person("Bob", 22));persons.add(new Person("Charlie", 19));// 将 Person 列表转换为只包含姓名的 String 列表List<String> names = persons.stream().map(Person::getName).collect(Collectors.toList());// 打印转换后的姓名列表System.out.println(names);}
}class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}
}

输出:

  [Alice, Bob, Charlie]

在上述示例中,我们有一个 Person 类,其中包含姓名和年龄属性。我们创建了一个 persons 列表,并添加了几个 Person 对象。

使用Stream,我们通过调用 map() 方法并传入一个方法引用 Person::getName,最后,我们使用 collect() 方法和 Collectors.toList() 将转换后的姓名收集到一个新的列表中。

API

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/205543.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Maven中常用命令以及idea中使用maven指南

文章目录 Maven 常用命令compiletestcleanpackageinstallMaven 指令的生命周期maven 的概念模型 idea 开发maven 项目idea 的maven 配置idea 中创建一个maven 的web 工程在pom.xml 文件添加坐标坐标的来源方式依赖范围编写servlet maven 工程运行调试 Maven 常用命令 compile …

腾讯云服务器99元一年?假的,阿里云是99元

腾讯云服务器99元一年是真的吗&#xff1f;假的&#xff0c;不用99元&#xff0c;只要88元即可购买一台2核2G3M带宽的轻量应用服务器&#xff0c;99元太多了&#xff0c;88元就够了&#xff0c;腾讯云百科活动 txybk.com/go/txy 活动打开如下图&#xff1a; 腾讯云服务器价格 腾…

C#中的var究竟是强类型还是弱类型?

前言 在C#中&#xff0c;var关键字是用来声明变量类型的&#xff0c;它是C# 3.0推出的新特征&#xff0c;它允许编译器根据初始化表达式推断变量类型&#xff0c;有点跟javascript类似&#xff0c;而javascript中的var是弱类型。它让C#变量声明更加简洁&#xff0c;但也导致了…

【Pytorch】Visualization of Fature Maps(2)

学习参考来自 使用CNN在MNIST上实现简单的攻击样本https://github.com/wmn7/ML_Practice/blob/master/2019_06_03/CNN_MNIST%E5%8F%AF%E8%A7%86%E5%8C%96.ipynb 文章目录 在 MNIST 上实现简单的攻击样本1 训练一个数字分类网络2 控制输出的概率, 看输入是什么3 让正确的图片分…

麻雀搜索优化算法MATLAB实现,SSA-BP网络

对于麻雀搜索算法的介绍&#xff0c;网上已经有不少资料了&#xff0c;这边公布SSA的matlab实现 下面展示SSA算法的核心代码以及详细注解 % 麻雀搜索算法函数定义 % 输入&#xff1a;种群大小(pop)&#xff0c;最大迭代次数(Max_iter)&#xff0c;搜索空间下界(lb)&#xff0c…

CSS实现空心的“尖角”

大家好&#xff0c;我是南宫&#xff0c;来分享一个昨天解决的问题。 我记得之前刷面试题的时候&#xff0c;CSS面试题里面赫然有一题是“如何用CSS实现三角形”&#xff0c;我觉得这个问题确实很经典&#xff0c;我上的前端培训班当初就讲过。 大概思路如下&#xff1a; 先…

想分析全国用电及煤气、液化石油气供应利用情况,这部分数据对你有帮助!

随着经济的发展和人民生活水平的提高&#xff0c;能源的需求量越来越大。其中&#xff0c;电力和煤气、液化石油气等能源的供应利用情况与我们的日常生活息息相关。 今天我们根据《中国城市统计年鉴》统计的中国地级及以上城市的煤气及液化石油气供应及利用情况的指标&#xff…

洗内裤的小洗衣机买啥牌子的?性价比婴儿洗衣机推荐

在近些年来&#xff0c;人们对生活和健康的要求越来越高&#xff0c;所以内衣洗衣机也走进了人们的视线&#xff0c;许多研究显示&#xff0c;单纯的手洗是不能彻底消除体内的细菌的&#xff0c;而机洗则可以有效地消除大部分的细菌&#xff0c;但是机洗内衣裤对洗衣机的卫生要…

MySQL数据库入门到大牛_基础_11_数据处理之增删改

本章将会介绍DML中的增删改查操作&#xff0c;增删改泛泛来讲是针对表中数据的修改。 文章目录 1. 插入数据1.1 实际问题1.2 方式1&#xff1a;VALUES的方式添加1.3 方式2&#xff1a;将查询结果插入到表中 2. 更新数据3. 删除数据4. 小结5. MySQL8新特性&#xff1a;计算列6. …

如何正确复制CSDN文章到自己的博客

1.csdn 文章页面&#xff0c;按f12打开浏览器开发者工具 2.按ctrl f 找 "article_content" 3.在该元素源代码上右键 “Copy”->“Copy element” 4.新建一个txt文件,把你粘贴的东西复制进去,然后再把文件名的后缀改为html,然后打开html文件,把里面的内容ctrlA全部…

【腾讯云云上实验室-向量数据库】腾讯云开创新时代,发布全新向量数据库Tencent Cloud VectorDB

前言 随着人工智能、数据挖掘等技术的飞速发展&#xff0c;海量数据的存储和分析越来越成为重要的研究方向。在海量数据中找到具有相似性或相关性的数据对于实现精准推荐、搜索等应用至关重要。传统关系型数据库存在一些缺陷&#xff0c;例如存储效率低、查询耗时长等问题&…