자바/스트림

스트림의 중간 연산(1)

백_곰 2022. 4. 13. 17:32

1. 스트림 자르기 - skip(), limit()

- skip() 메서드는 지정한 매개변수만큼 스트림의 요소를 건너뛴다.

 

- limit() 메서드는 지정한 매개변수만큼 스트림의 요소를 제한한다.

 

- 기본형 Stream에서도 정의되어 있다.

 

IntStream intStream = IntStream.rangeClosed(1, 10);

// 1~10을 가진 intStream 변수

 

intStream.skip(3).limit(5).forEach(System.out::println);

// 4, 5, 6, 7, 8 출력한다.

 

 

 

 

2. 스트림의 요소 걸러내기 - filter(), distinct()

- filter()는 주어진 조건에 맞게 스트림의 요소를 걸러낸다. 사용방법은 아래의 코드를 보자.

 

IntStream intStream = IntStream.rangeClosed(1, 10)

intStream.filter(i -> i%2==0).forEach(System.out::print)

// 2, 4, 6, 8, 10 출력

 

( 조건식이 두 개 이상이라면 괄호 () 안에 한꺼번에 넣어도 된다. )

( 또한 filter(조건식).filter(조건식)도 가능하다. )

 

 

- distinct()는 스트림에서 중복된 요소를 제거한다. 사용방법은 아래의 코드를 보자.

 

IntStream intStream = IntStream.of(1,2,2,3,3,4)

intStream.distinct().forEach(System.out::print)

// 1, 2, 3, 4 출력

 

 

 

 

3. 정렬 - sorted()

- sorted() 메서드는 지정된 Comparator로 스트림을 정렬하는데, int로 반환하는 람다식 또한

가능하다.

 

- 만약 Comparator를 지정하지 않으면, 스트림 요소의 기본 정렬은 Comparable로 정렬된다.

 

- 단, 요소가 Comparable을 구현한 클래스가 아니라면 예외가 발생한다.

 

- 아래의 문자열 스트림 정렬 방법을 보고 이해하자.

( 앞에 참조변수 생략함. )

 

Stream<T> sorted(Comparator<? super T> comparator)

 

(1) 기본 정렬

: sorted()

: sorted(Comparator.naturalOrder())

: sorted((s1,s2) -> s1.compareTo(s2))

: sorted(String::compareTo)

 

 

(2) 기본 정렬의 역순

: sorted(Comparator.reverseOrder())

: sorted(Comparator.<String>naturalOrder().reversed())

 

 

(3) 대소문자 구분안함

: sorted(String.CASE_INSENSITIVE_ORDER)

 

: sorted(String.CASE_INSENSITIVE_ORDER.reversed())

// 역순으로 정렬

 

 

(4) 길이 순 정렬

: sorted(String.comparing(String::length))

 

: sorted(String.comparingInt(String::length))

// 오토박싱 안함.

 

 

( JDK1.8부터 Comparator 인터페이스에 static 메서드와 디폴트 메서드가 많이 추가되었다. )

( 그러므로 아래의 링크에 들어가서 직접 보면서 필요한 부분이 있으면 쓰는 것이 좋다. )

Comparator (Java Platform SE 8 ) (oracle.com)

 

Comparator (Java Platform SE 8 )

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. In the foregoing description, the notation sgn(expression) designates the mathematical s

docs.oracle.com

 

 

( 그 중 comparing()아래에 나와있는 대로 가장 기본적인 메서드이다. )

( 이 두 개의 메서드 중에서 만약 스트림의 요소가 Comparable로 구현하였다면, 위 매개변수 하나만 있는 것을

사용하면 된다. )

 

( 그렇지 않은 경우, 밑에 메서드를 사용하는데, 따로 Compartor를 따로 지정해야 한다. )

 

 

( 만약 comparing()에 대한 메서드를 오토박싱과 언박싱 없이 사용하고 싶다면 아래의 메서드를 사용하면 된다. )

 

( 만약 정렬 조건을 추가할 때는 아래의 사진에 있는 thenComparing()를 이용한다. )

( 예를 들어, 학생 스트림을 반별, 성적순, 이름순으로 정렬하여 출력하려면 다음과 같이 한다. )

studentStream.sorted(Comparator.comparing(Student::getBan)

                                       .thenComparing(Student::getTotalScore)

                                       .thenComparign(Student::getName)). forEach(System.out::println);

 

 

 

 

3-1. 정렬을 이해하기 위한 예제(1) - comparing, thenComparing

: 이 예제는 학생의 성적을 반별 오름차순, 총점별 내림차순으로 정렬하여 출력하는 예제이다.

 

 

( 기본 정렬은 Student 클래스의 compareTo() 메서드에 정의하였다. )