1. 기본타입
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
public class SortedExample {
public static void main(String[] args) {
int[] arr = {1,8,4,7,9,6,10};
IntStream intStream = Arrays.stream(arr);
intStream.sorted().forEach(System.out::println);
}
}
2. 참조타입
public class Person implements Comparable<Person>{
private String name;
private int score;
public Person(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
@Override
public int compareTo(Person p) {
return Integer.compare(this.score, p.score); // 오름차순
// Integer.compare(p.score, this.score) 내림차순
}
}
import java.util.Arrays;
import java.util.List;
public class SortedExample {
public static void main(String[] args) {
List<Person> list = Arrays.asList(
new Person("lee",88),
new Person("kim",84),
new Person("hong",99),
new Person("park",73),
new Person("moon",78)
);
// Person 객체는 Compare 인터페이스를 구현해야한다.
list.stream().sorted().mapToInt(Person::getScore).forEach(System.out::println);
}
}
// Comparable 인터페이스에서 구현한 기준과 반대로 정렬
list.stream().sorted(Comparator.reverseOrder())
.mapToInt(Person::getScore).forEach(System.out::println);
[Stream] 스트림 Matching : allMatch, anyMatch, noneMatch (0) | 2020.06.18 |
---|---|
[Stream] 스트림 peek (0) | 2020.06.18 |
[Collection : List] 배열 병합 addAll() (0) | 2020.06.17 |
[System] 배열 병합 arraycopy(src,srcPos,dest,length) 예제 (0) | 2020.06.17 |
[Stream 스트림] flatMap() 2차원 배열 내의 1차원 배열 요소의 중간처리 (0) | 2020.06.17 |
댓글 영역