class Person{
String username;
int score;
public Person() {}
public Person(String username, int score) {
this.username = username;
this.score = score;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [username=" + username + ", score=" + score + "]";
}
}//end class
sorted : 정렬
List<Person> list = Arrays.asList(new Person("홍길동1", 100),
new Person("홍길동2", 80),
new Person("홍길동3", 85),
new Person("홍길동4", 90),
new Person("홍길동5", 70));
오름차순
//오름차순: Person클래스의 score값 기준
list.stream()
// .sorted(Comparator.comparing(Person::getScore))
.sorted(Comparator.comparingInt(Person::getScore))
.forEach(System.out::println);
System.out.println();
//Student [username=홍길동5, score=70]
//Student [username=홍길동2, score=80]
//Student [username=홍길동3, score=85]
//Student [username=홍길동4, score=90]
//Student [username=홍길동1, score=100]
내림차순
//내림차순: Person클래스의 score값 기준
list.stream()
.sorted(Comparator.comparing(Person::getScore, Comparator.reverseOrder()))
.forEach(System.out::println);
System.out.println();
//Student [username=홍길동1, score=100]
//Student [username=홍길동4, score=90]
//Student [username=홍길동3, score=85]
//Student [username=홍길동2, score=80]
//Student [username=홍길동5, score=70]
---
skip(n) : n개가 skip됨
list.stream()
// .sorted(Comparator.comparing(Person::getScore))
.sorted(Comparator.comparingInt(Person::getScore))
.skip(2)
.forEach(System.out::println);
System.out.println();
//Student [username=홍길동3, score=85]
//Student [username=홍길동4, score=90]
//Student [username=홍길동1, score=100]
limit(n) : n개 얻기
list.stream()
// .sorted(Comparator.comparing(Person::getScore))
// .sorted(Comparator.comparingInt(Person::getScore))
.limit(3)
.forEach(System.out::println);
System.out.println();
//Student [username=홍길동1, score=100]
//Student [username=홍길동2, score=80]
//Student [username=홍길동3, score=85]
'Programming Language > JAVA' 카테고리의 다른 글
자바 스트림 API - 최종처리_allMatch/anyMatch/noneMatch (0) | 2023.09.08 |
---|---|
자바 스트림 API- 중간처리(3)_boxed/asDoubleStream() (0) | 2023.09.07 |
자바 스트림 API - 중간처리(1)_distinct/filter/map/mapToInt/flatmap (1) | 2023.09.07 |
자바 스트림 API - 스트림 생성 (0) | 2023.09.07 |
자바 스트림 API (java stream API) (0) | 2023.09.07 |