MapleStory Cookie With Halo

☕ JAVA/☕ Class & Method

[JAVA][Stream]중간 연산-filter() distinct() skip() limit() sorted()

뉴이 NUEY 2024. 12. 16. 02:01
반응형

 

중간 연산의 종류

 

중간 연산 설명
Stream<T>  distinct() 중복 제거.
Stream<T>  filter(Predicate<T> predicate) 조건에 맞지 않는 요소 제거.
Stream<T>  limit(long maxSize) 스트림 일부 잘라내기.
Stream<T>  skip(long n) 스트림 일부 건너뛰기.
Stream<T>  peek(Consumer<T> action) 작업 중간을 확인할 때 사용한다.
Stream<T>  sorted()
Stream<T>  sorted(Comparator<T> comparator)
요소 정렬
Stream<R>
DoubleStream
IntStream
LongStream
map(Function<T, R> mapper)
mapToDouble(ToDoubleFunction<T> mapper)
mapToInt(ToIntFunction<T> mapper)
mapToLong(ToLongFunction<T> mapper)
스트림의 요소를 변환한다.
Stream<R>
DoubleStream
IntStream
LongStream
flatMap(Function<T, Stream<R>> mapper)
flatMapToDouble(Function<T,Doublestream> m)
flatMapToInt(Function<T, Intstream> m)
flatMapToLong(Function<T, Longstream> m)

 

🌟 중간 연산은 모두 Stream을 반환합니다.

 


 

skip(long n)
: 앞에서부터 n개 건너뛰기.

rangedClosed()를 이용해 1부터 10까지 가진 Stream을 만들었습니다.

 

skip(3)이라 앞에 세자리를 띈 스트림을 반환했습니다.

 


 

limit(long maxSize)
: maxSize 이후의 요소는 잘라낸다.

5번째 이후의 숫자를 잘라낸 스트림을 반환했습니다.

 


 

distinct()
: 중복제거.

arr에서 중복되는 요소를 지워줍니다.

 


 

filter(조건)
: 조건에 맞지 않는 요소는 걸러낸다.

2와 3의 배수만 남기고 모두 걸러졌습니다.

 


 

sorted(기준)
: 요소를 정렬한다.

sorted( )로 쓰면 기본정렬된다.

 

sorted(Comparator.naturalOrder())도 동일하게 기본정렬이다.

 

🌟 sorted(Comparator.reverseOrder()) : 거꾸로 정렬한다.

 


 

sorted(람다식 or 메서드참조)

람다식을 이용해서 기본 정렬하기
i1와 i2의 자리를 바꾸면 거꾸로 정렬된다.

 

 

메서드 참조로 적어보기. 기본정렬된다.

 


 

.sorted(String.CASE_INSENSITIVE_ORDER)
: 문자열을 정렬해준다.
(대소문자 구분❌)

🌟 거꾸로 정렬하고 싶을 때는 String.CASE_INSENSITIVE_ORDER.reversed()로 적어준다.

 


 

.sorted(Comparator.comparing(String::length))
: 문자열길이로 정렬하기.

문자열 길이가 길수록 뒤로간다.

 

💡 Comparator의 comparing(입력데이터 타입, 기준)
🌟 추가 정렬기준을 제공할 때는 thenComparing()을 사용한다.

 

출력결과

  • Comparator.comparing(Student::getBan)
    → 입력값은 Student이고, 기준 정렬은 ban이다.

  • 이후 추가로 정렬기준을 더하기 위해 thenComparing()을 사용하였다.

  • thenComparing()의 기본정렬은 Student클래스에 정의된 compareTo()이다. (총점 높은 순)

 


참조영상1

참조영상2

반응형