스트림은 요소가 최종 처리되기 전에 중간 단계에서 요소를 정렬하여 최종 처리 순서를 변경

 

객체 요소일 경우에는 클래스가 Comparable을 구현하지 않고 있으면 sorted() 메소드를 호출했을 때 ClassCastException이 발생

즉, Comparable을 구현한 요소에서만 sorted() 메소드를 호출해야 함

 

기본 비교 방법으로 정렬하고 싶다면 (오름차순)

sorted();
또는
sorted( Comparator.naturalOrder() );

 

기본 비교 방법과 정반대 방법으로 정렬하고 싶다면 (내림차순)

sorted( Comparator.reverseOrder() );

 

객체 요소가 Comparable을 구현하지 않았다면 Comparator를 매개값으로 갖는 sorted() 메소드를 사용하면 됨

 

정렬 가능한 클래스

package sec06.stream_sorting;

public class Student implements Comparable<Student> {
	private String name;
	private int score;
	
	public Student(String name, int score) {
		this.name = name;
		this.score = score;
	}

	public String getName() {
		return name;
	}

	public int getScore() {
		return score;
	}

	@Override
	public int compareTo(Student o) {
		return Integer.compare(score, o.score);
	}	
}

 

정렬

package sec06.stream_sorting;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;

public class SortingExample {
	public static void main(String[] args) {
		//숫자 요소
		IntStream intStream = Arrays.stream(new int[] {5, 3, 2, 1, 4});
		intStream
			.sorted() //숫자를 오름차순으로 정렬
			.forEach( n -> System.out.print(n+ ","));
		System.out.println();
		
		//객체 요소
		List<Student> studentList = Arrays.asList(
			new Student("홍길동", 30),
			new Student("신용권", 10),
			new Student("유미선", 20)
		);
		
		studentList.stream()
			.sorted() //점수를 기준으로 오름차순 정렬
			.forEach( s -> System.out.print(s.getScore() + ","));
		System.out.println();
		
		studentList.stream()
			.sorted( Comparator.reverseOrder() ) //점수를 기준으로 내림차순 정렬
			.forEach( s -> System.out.print(s.getScore()+ ","));
	}
}
1,2,3,4,5,
10,20,30,
30,20,10,

+ Recent posts