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;
}
}
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));
List<Student> studentFilter = students.stream()
.filter(student -> student.name.equals("zhangsan"))
.collect(Collectors.toList());
studentFilter.stream().forEach(student -> System.out.println("zhangsan的分数:" + student.score));
System.out.println("分数80以上的人数:" + students.stream().filter(student -> student.score > 80).count());
List<Student> studentsScoreOver60 = students.stream()
.filter(student -> student.score > 60)
.collect(Collectors.toList());
studentsScoreOver60.stream().forEach(student -> System.out.println(student.name + "分数是:" + student.score));
students.stream()
.filter(student -> student.score >= 80)
.limit(2)
.forEach(student -> System.out.println(student.name + "的分数:" + student.score));
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();
}
}
}