JAVA

Java Stream API 주요 메서드 정리

도원좀비 2025. 2. 28. 14:58

1. 스트림생성

 

메서드 설명 예제
Stream.of(T... values) 개별 요소로 스트림 생성 Stream.of(1, 2, 3, 4)
Arrays.stream(T[] array) 배열을 스트림으로 변환 Arrays.stream(new int[]{1, 2, 3})
Collection.stream() 리스트, 셋 등의 컬렉션을 스트림으로 변환 List.of(1,2,3).stream()

 

2. 필터링 (Filtering)

메서드 설명 예제
filter(Predicate<T> predicate) 조건을 만족하는 요소만 남김 list.stream().filter(n -> n > 5)
distinct() 중복 요소 제거 list.stream().distinct()

 

3. 변환 (Mapping)

메서드 설명 예제
map(Function<T,R>mapper) 요소를 다른 값으로 변화 list.stream().map(n -> n * 2)
mapToInt(ToIntFuction<T>mapper) 요소를 int로 변환 list.stream().mapToInt(String::length)
flatMap(Function<T,Stream<R>> mapper) 중첩된 스트림을 평탄화 list.stream().flatMap(List::steam)

 

4. 정렬 (Sorting)

 

메서드 설명 예제
sorted() 오름차순 정렬 list.stream().sorted
sorted(Comparator<T>comparator) 특정 기준으로 정렬 list.stream().sortes(Comparator.reverseOrder)

 

5. 반복 처리 (Iterating)

메서드 설명 예제
forEach(Consumer<T>action) 각요소를 순회하며 처리 list.stream().forEach(System.out::println)
peek(Consumer<t>action) 중간 연산에서 디버긴 용도로 사용 list.stream().peel(System.out::prinln).collect(Collctors.toList())

 

6. 집계 (Reduction)

메서드 설명 예제
count() 요소 개수 반환 list.stream().count()
sum() 합계 계산(IntStream, DoublStream 등에서 사용) list.stream().mapToInt(n -> n).sum()
max(Comparator<T>comparator) 최대값 찾기 list.stream().max(Integer::compareTo)
min(Comparator<T>comparator) 최소값 찾기 list.stream().min(Integer::comapreTo)
reduce(BinartOperator<T>accumulator) 누적하여 값을 계산 list.stream().reduce(0, (a, b) -> a+b)

 

7. 수집 (Collecting)

메서드 설명 예제
collect(Collectors.toList()) 리스트로 변환 list.stream().collect(Collectors.toList())
collect(Collectors.toSet()) 집합(Set)으로 변환 list.stream().collect(Collectors.toSet())
collect(Collectors.toMap(Funtion<T,K>
keyMapper, Function<T,V> valueMapper))
맵(Map)으로 변환 list.Stream().collect((Collectors.toMap
(String::length, Function.identity()))
collect(Collectors.joining(",")) 문자열로 결합 list.stream().map(String::valueOf)
.collect(Collctors.join(","))
collect(Collectors.summingInt(ToIntFunction
<T>mapper))
숫자를 합계 계산 list.stream().collect(Collectors.summingInt
(n -> n))
collect(Collectors.groupingBy(Function<T,K>
classifier))
그룹화 list.stream().collect(Collectors.groupingBy
(String::length))

 

8. 매칭 (Matching)

메서드 설명 예제
anyMatch(Predicate<T>predicate) 하나라도 조건을 만족하면 true list.stream().anyMatch(n -> n >10)
allMatch(Predicate<T>predicate) 모든 요소가 조건을 만족하면 true list.stream().allMatch(n -> n < 0)
noneMatch(Predicate<T>predicate) 모든 요소가 조건을 만족하지 않으면 true list.stream().noneMatch(n -> n < 0)

 

9. 요소 찾기 (Finding)

메서드 설명 예제
findFirst() 첫 번째 요소 반환 list.stream().findFirst()
findAny() 아무 요소나 반환( 병렬 스트림에서 유용) list.stream().findAny()

 

10. 스트림 종료 (Short-Circuiting)

메서드 설명 예제
limit(long maxSize) 최대 maxSize개의 요소만 반환 list.stream().limit(3)
skip(long n) 처음 n개의 요소를 건너뜀 list.stream().skip(2)

 

 

1. 숫자 리스트에서 짝수만 골라 제곱 후 합계 구하기

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

        int sum = numbers.stream()
                .filter(n -> n % 2 == 0)  // 짝수만 선택
                .map(n -> n * n)         // 제곱
                .reduce(0, Integer::sum); // 합계 계산

        System.out.println(sum); // 56 (2^2 + 4^2 + 6^2)
    }
}

 

2. 문자열 리스트를 길이별로 그룹화 

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cat", "dog", "elephant");

        Map<Integer, List<String>> grouped = words.stream()
                .collect(Collectors.groupingBy(String::length));

        System.out.println(grouped);
    }
}

'JAVA' 카테고리의 다른 글

쓰레드 동기화 (Synchronization)  (3) 2025.03.11
쓰레드(Thread)  (0) 2025.03.11
자바 기본 다지기 최종  (2) 2025.02.27
자바 기초 문법 다지기 4  (1) 2025.02.26
자바 기초 문법 다지기 3  (1) 2025.02.26