java Stream流的筛选、排序
java Stream流的筛选、排序
package lambda_stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Student {
public int id;
public String name;
public double score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Student() {
// 重载了构造方法,默认的构造方法就失效了,如果要用默认的构造方法,就要再次进行说明
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Student(int id, String name, double score) {
this.id = id;
this.name = name;
this.score = score;
}
}
/**
* 流的处理:
* 流的创建(通过已有集合studentList.stream()、Stream.of())
* 中间操作(filter(筛选,过滤)、map(映射)、sorted(排序)、limit(返回前n个)、skip(去掉前n个)、distinct(去重))得到的结果还是一个stream
* 最终操作(count(统计流中个数)、forEach(迭代遍历)、collect(规约转换成集合))
*/
class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(1, "zhangsan", 100));
students.add(new Student(5, "cuiting", 80));
students.add(new Student(2, "lisi", 80));
students.add(new Student(3, "wangwu", 60));
students.add(new Student(4, "zhaoliu", 40));
// 查找姓名为zhangsan的学生,打印分数
List<Student> studentFilter = students.stream()
.filter(student -> student.name.equals("zhangsan"))
.collect(Collectors.toList());
studentFilter.stream().forEach(student -> System.out.println("zhangsan的分数:" + student.score));
// 统计学生分数80以上的人数
System.out.println("分数80以上的人数:" + students.stream().filter(student -> student.score > 80).count());
// 查找分数大于60的学生集合
List<Student> studentsScoreOver60 = students.stream()
.filter(student -> student.score > 60)
.collect(Collectors.toList());
studentsScoreOver60.stream().forEach(student -> System.out.println(student.name + "分数是:" + student.score));
// 打印80即以上的2名同学的姓名和分数
students.stream()
.filter(student -> student.score >= 80)
.limit(2)
.forEach(student -> System.out.println(student.name + "的分数:" + student.score));
// 根据分数升序排序,分数相同根据id升序排序:多字段排序
List<Student> orderStudents = students.stream()
.sorted(Comparator.comparing(Student::getScore).thenComparing(Student::getId))
.collect(Collectors.toList());
orderStudents.stream().forEach(student -> System.out.println(student.name+"排序的分数:"+student.score));
// 分组统计不同分数的同学
Map<Double,List<Student>> studentMap = students.stream().collect(Collectors.groupingBy(Student::getScore));
for (List<Student> value : studentMap.values()){
value.stream().forEach(student -> System.out.print(student.name+":"+student.score+" "));
System.out.println();
}
}
}
上一篇:
IDEA上Java项目控制台中文乱码
