JAVA chapter16. 스트림과 병렬처리. 


16.6 정렬(sorted())



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
    
        /* 
         score < o.score : 음수 리턴
         score == o.score : 0 리턴
         score > o.score : 양수 리턴 
         */ 
        
         /* 
           if(score < o.score) return -1;
           else if(score == o.score) return 0;
           else return 1;
         */
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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[] {53214});
        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() + ","));    
    }
}
cs



Posted by 너래쟁이
: