limit: 限制,截取流中指定数量的元素 skip: 跳过,跳过流中的指定数量的元素 package Stream ; import lombok . * ; import java . util . Objects ; /** * @Author yqq * @Date 2021/10/17 16:55 * @Version 1.0 */ @Getter @
limit: 限制,截取流中指定数量的元素
skip: 跳过,跳过流中的指定数量的元素
import lombok.*;
import java.util.Objects;
/**
* @Author yqq
* @Date 2021/10/17 16:55
* @Version 1.0
*/
public class Student implements Comparable<Student>{
private String name;
private Integer age;
private Integer score;
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return name.equals(student.name) && age.equals(student.age) && score.equals(student.score);
}
public int hashCode() {
return Objects.hash(name, age, score);
}
public int compareTo(Student o) {
return score - o.score;
}
}package Stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @Author yqq
* @Date 2021/10/17 13:40
* @Version 1.0
*/
public class demo01 {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Collections.addAll(list,
new Student("lishi",22,20),
new Student("zhangshan",23,28),
new Student("wanger",24,19),
new Student("mazi",25,29),
new Student("mazi",25,29)
);
list.stream().sorted((s1,s2) -> s2.getScore()-s1.getScore())
.distinct()
.limit(3)//获取成绩的前3名,
.skip(2)//获取成绩的第3名,
.forEach(System.out::println);
}
}