返回
Java8中Stream的常用操作方式大全
后端
2023-12-08 01:00:29
[TOC]
一、前期准备
1、创建对象
1.1、Student
public class Student {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
2、初始化数据
2.1、初始化集合
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, 90.0));
students.add(new Student("李四", 19, 80.0));
students.add(new Student("王五", 20, 70.0));
students.add(new Student("赵六", 21, 60.0));
students.add(new Student("孙七", 22, 50.0));
二、Stream常用操作方式
1、筛选
1.1、filter
filter()方法用于筛选出满足指定条件的元素。
List<Student> filteredStudents = students.stream()
.filter(student -> student.getScore() > 80.0)
.toList();
1.2、limit
limit()方法用于限制返回的元素个数。
List<Student> limitedStudents = students.stream()
.limit(2)
.toList();
1.3、skip
skip()方法用于跳过指定数量的元素,然后返回剩余的元素。
List<Student> skippedStudents = students.stream()
.skip(2)
.toList();
2、聚合
2.1、count
count()方法用于计算流中元素的个数。
long count = students.stream()
.count();
2.2、sum
sum()方法用于计算流中元素的和。
double sum = students.stream()
.mapToDouble(Student::getScore)
.sum();
2.3、average
average()方法用于计算流中元素的平均值。
double average = students.stream()
.mapToDouble(Student::getScore)
.average()
.getAsDouble();
2.4、max
max()方法用于返回流中元素的最大值。
Student maxStudent = students.stream()
.max(Comparator.comparing(Student::getScore))
.get();
2.5、min
min()方法用于返回流中元素的最小值。
Student minStudent = students.stream()
.min(Comparator.comparing(Student::getScore))
.get();
3、排序
3.1、sorted
sorted()方法用于对流中的元素进行排序。
List<Student> sortedStudents = students.stream()
.sorted(Comparator.comparing(Student::getScore).reversed())
.toList();
4、匹配
4.1、allMatch
allMatch()方法用于判断流中的所有元素是否都满足指定条件。
boolean allMatch = students.stream()
.allMatch(student -> student.getScore() > 80.0);
4.2、anyMatch
anyMatch()方法用于判断流中的任何一个元素是否满足指定条件。
boolean anyMatch = students.stream()
.anyMatch(student -> student.getScore() > 90.0);
4.3、noneMatch
noneMatch()方法用于判断流中的没有元素满足指定条件。
boolean noneMatch = students.stream()
.noneMatch(student -> student.getScore() < 60.0);
5、查找
5.1、findFirst
findFirst()方法用于返回流中的第一个元素。
Student firstStudent = students.stream()
.findFirst()
.get();
5.2、findAny
findAny()方法用于返回流中的任意一个元素。
Student anyStudent = students.stream()
.findAny()
.get();