2022.05.19 - [CodeStates/Enum,Annotation,Stream,람다] - [CodeStates] 람다(Lambda), 스트림 생성(Stream)
[CodeStates] 람다(Lambda), 스트림 생성(Stream)
# 람다(Lambda) 람다식은 익명함수(anonymous function)로 구동됩니다. 람다식은 마치 함수처럼 작성하지만, 실행시 익명구현 객체를 생성하는 방식으로 구동되며 병렬처리, 이벤트 처리 등 함수적 프
jungdo8016.tistory.com
# 스트림 중간 연산
주요 중간 연산에는
- filter
- map
- sorted
* filter
filter() 메서드는 조건에 맞는 요소들만 걸러주는 역할을 합니다.
int[] arr = {0, 2, 3, 5, 6, 7, 7, 4, 4, 10};
IntStream stream = Arrays.stream(arr);
stream.filter(n -> n % 2 != 0).forEach(e -> System.out.print(e + " "));
3 5 7 7
위 코드에서는 filter 내에서 stream 내부에 있는 요소들 중 짝수가 아닌것들만 걸러 달라고 명령하고 있습니다. 이처럼 filter 안에는 boolean 타입이 출력될 수 있도록 설정하여야 합니다.
filter와 많이 쓰이는 메서드 중에는 distinct() 라는 것이 있습니다. 해당 메서드는 stream 내에 중복을 제거하는 역할을 수행합니다.
int[] arr = {0, 2, 3, 5, 6, 7, 7, 4, 4, 10};
IntStream stream = Arrays.stream(arr);
stream.filter(n -> n % 2 != 0).distinct().forEach(e -> System.out.print(e + " "));
3 5 7
distinct()을 설정하기 전 결과값은 "3 5 7 7"이었습니다. 그러나 distinct()를 통해 중복된 요소들을 제거하게 됨으로써 기존에 중복되었던 7이 한 개만 출력되게 된 것입니다.
* map
map() 메소드는 해당 스트림의 요소들을 주어진 함수를 통해 새로운 스트림으로 반환해 주는 역할을 수행합니다.
Stream<String> strStream = Stream.of("bbb", "aaa", "C", "cc", "hello");
strStream.map(m -> m.length()).forEach(e -> System.out.print(e + " "));
3 3 1 2 5
위 코드에서 map은 문자열들을 그 크기값으로 변환하여 새로운 Stream 반환해 주는 역할을 수행합니다.
map과 비슷한 개념이지만 좀 더 심화된 개념의 flatmap()이라는메서드가 있습니다. flatmap은 중첩 구조를 한 단계 제거하고 단일 컬렉션으로 만들어주는 역할을 합니다. 이러한 작업을 플래트닝(flattening)이라고 합니다.
List<List<String>> list =
Arrays.asList(Arrays.asList("aaa"), Arrays.asList("bbb"));
List<String> flatList = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
[aaa,bbb]
참고로 flatMap안에 있는 Collection::stream에서 :: 왼쪽 객체의 오른쪽 메서드를 사용하겠다는 뜻입니다. 예를들어 String::toLowerCase의 경우 String 객체의 toLowerCase를 통해 문자를 소문자로 바꿔 주겠다는 의미입니다.
* sorted
sorted()는 쉽게 stream 요소들을 정렬할 수 있는 메서드입니다.
Stream<String> stream1 = Stream.of("bbb", "aaa", "C", "cc", "hello");
stream1.sorted().forEach(s -> System.out.print(s + " "));
C aaa bbb cc hello
단순히 .sorted()를 추가하면 문자열, 숫자 등이 오름차순으로 정렬되게 됩니다. 반대로 내림차순으로 정렬하는 것도 가능합니다.
Stream<String> stream2 = Stream.of("bbb", "aaa", "C", "cc", "hello");
stream2.sorted(Comparator.reverseOrder()).forEach(s -> System.out.print(s + " "));
hello cc bbb aaa C
'JAVA > Enum,Annotation,Stream,람다' 카테고리의 다른 글
람다(Lambda)와 스트림 생성(Stream)에 대해 배워보자 (0) | 2022.05.19 |
---|---|
열거형(Enum)과 어노테이션(Annotation)에 대해 배워보자 (0) | 2022.05.19 |