본문 바로가기
Language/JAVA

스트림(Stream) 의 특징

by YoonJong 2023. 2. 13.
728x90

스트림은 컬렉션이나 배열의 다양한 데이터 소스를 표준화된 방법으로 다루기 위한 것입니다.

데이터소스를 추상화하고 데이터를 다루는데 자주 사용되는 메서드 들이 정의되어 있습니다.

 

스트림을 이용하는 방법은 보통 3단계로 이루어집니다.

1. 스트림 만들기

2. 중간 연산 n 번

3. 최종 연산 1번

자바의 정석

 

스트림의 특징을 알아보겠습니다

1. 스트림은 데이터 소스로부터 데이터를 읽기만할 뿐 변경하지 않습니다.

public class StreamEx_1 {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(3, 1, 5, 4, 2);
        List<Integer> stream = list.stream().sorted().collect(toList());

        System.out.println("list = " + list);
        System.out.println("stream = " + stream);

    }
}

// 결과값
list = [3, 1, 5, 4, 2]
stream = [1, 2, 3, 4, 5]

2. 스트림은 일회용입니다. 필요하면 다시 스트림을 생성해야 합니다.

List<Integer> list = Arrays.asList(3, 1, 5, 4, 2);
list.stream().forEach(System.out::println);
list.count(); // 불가

3. 최종 연산 전까지 중간연산이 수행되지 않습니다. 

// 로또번호 출력 
IntStream intStream = new Random().ints(1, 46); // 무한 스트림
intStream.distinct().limit(6).sorted() // 중간 연산
        .forEach(num -> System.out.print(num + " ")); // 최종 연산

4. 스트림의 작업을 병렬 처리 시킬 수 있습니다. - 빅데이터 처리시 여러 쓰레드가 동시에 작업할 수 있습니다.

// 병렬스트림 - 빅데이터 처리 시 사용
Stream<String> stringStream = Stream.of("dd", "aaa", "cc", "CC", "b");
int result = stringStream.parallel() // 병렬 스트림으로 전환
        .mapToInt(s -> s.length()).sum();

// 결과값
10

 

728x90

댓글