Java中Stream的常用方法
题目要求
从上述集合中找到成绩最高的三位学员的分数,不能重复[99,92,90],要求只统计年龄大于15的学生
public class Student {
private int ID;
private String name;
private int age;
private int score;
private String aiHao;
public Student() {
}
public Student(int ID, String name, int age, int score, String aiHao) {
this.ID = ID;
this.name = name;
this.age = age;
this.score = score;
this.aiHao = aiHao;
}
public int getID() {
return ID;
}
public Student setID(int ID) {
this.ID = ID;
return this;
}
public String getName() {
return name;
}
public Student setName(String name) {
this.name = name;
return this;
}
public int getAge() {
return age;
}
public Student setAge(int age) {
this.age = age;
return this;
}
public int getScore() {
return score;
}
public Student setScore(int score) {
this.score = score;
return this;
}
public String getAiHao() {
return aiHao;
}
public Student setAiHao(String aiHao) {
this.aiHao = aiHao;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return ID == student.ID &&
age == student.age &&
score == student.score &&
Objects.equals(name, student.name) &&
Objects.equals(aiHao, student.aiHao);
}
@Override
public int hashCode() {
return Objects.hash(ID, name, age, score, aiHao);
}
//添加默认排序方法
@Override
public String toString() {
return "Student{" +
"ID=" + ID +
", name='" + name + '\'' +
", age=" + age +
", score=" + score +
", aiHao='" + aiHao + '\'' +
'}';
}
}
Main方法
public class Test{
private static List<Student> list = new ArrayList<>();
static{
list.add(new Student(10,"张三",18,89,"唱歌"));
list.add(new Student(15,"李四",16,90,"跳舞"));
list.add(new Student(12,"王五",15,95,"游泳"));
list.add(new Student(11,"赵六",17,92,"跑步"));
list.add(new Student(18,"孙七",19,90,"蓝球"));
list.add(new Student(16,"周八",15,91,"足球"));
list.add(new Student(14,"吴九",20,99,"羽毛球"));
list.add(new Student(17,"郑十",14,93,"上网"));
}
public static void main(String[] args){
//这里会用Lambda来编写
//将集合转换为Stream流
Stream<Student> str = list.stream();
/*
过滤掉15岁以下的学生
*/
Stream<Student> str01 = str.filter(student -> student.getAge() > 15);
/*
提取出成绩
*/
Stream<Integer> str02 = str01.map(student -> student.getScore());
/*
去重
*/
Stream<Integer> str03 = str02.distinct();
/*
排序(倒序)
*/
Stream<Integer> str04 = str03.sorted(Comparator.reverseOrder());
/*
截取前三名
*/
Stream<Integer> str05 = str04.limit(3);
/*
再将Stream流转换为集合
*/
List<Integer> li = str05.collect(Collectors.toList());
System.out.println(li);//[99, 92, 90]
}
}
这里还可以用链式编写,因为每次调用方法都是返回的一个Stream类型
Stream<Student> str = new list.stream();
List<Integer> li = str.filter(student -> student.getAge() > 15)
.map(student -> student.getScore())
.distinct()
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
System.out.println(li);//[99, 92, 90]