본문 바로가기

개발지/Today I learn

[0830] 자바 스트림 (스트림 파이프라인 - 1. 스트림의 생성)

#스트림 파이프라인 - 1. 스트림의 생성

- 배열 스트림 생성은 Arrays 클래스 stream() 또는 Sream 클래스의 of() 메서드를 사용한다.

public class StreamCreator {
    public static void main(String[] args) {
        String[] arr = enw String[]{"대한민국", "일본", "중국"};
        
        // 문자열 스트림 생성 (Arrays 클래스 메서드 사용)
        Stream<String> stream1 = Arrays.stream(arr);
        // 문자열 스트림 생성 (Stream 클래스 메서드 사용)
        Stream<String> stream2 = Stream.of(arr);
        
        stream1.forEach(System.out::println);
        stream2.forEach(System.out::println);
    }
}

 

- Arrays 클래스의 IntStream

  ▪ 숫자 연산과 관련된 대부분의 메서드 존재.

  ▪ 메서드는 최종 연산지이므로 사용 시, 스트림이 닫히게 된다.

public class StreamExample {

    public static void main(String[] args) {
        int[] intArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        // Arrays 클래스 IntStream
        IntStream intStream = Arrays.stream(intArr);
        
        System.out.println("배열의 모든 수의 합은 " + intStream.sum());
        // 최종 연산자 이후 스트림이 닫힘
        // System.out.println("배열의 모든 수의 평균은 " + intStream.average());
    }
}
//출력값
배열의 모든 수의 합은 55

 

- 컬렉션 스트림 생성은 Collection 클래스의 stream() 메서드를 사용한다.

public class StreaCreator {
    public static void main(String[] args) {
    
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
        Stream<Integer> stream = list.stream();
        
        stream.forEach(System.out::print);
    }
}

  ▪ Collection 하위클래스 ListSet을 구현한 클래스 모두 stream() 메서드를 사용하여 스트림 생성이 가능하다.

 

- 임의의 수 스트림 생성

  ▪ 난수를 생성하는 자바의 기본 내장 클래스 Random 클래스 안의 스트림 생성 메서드를 사용한다.

public class StreamCreator {
    public static void main(String[] args) {
        IntStream ints = new Random().ints();
        ints.forEach(System.out::println);
    }
}

// 위 코드는 int형 범위 내의 수를 무작위로 출력한다
// 스트림의 크기가 정해지지 않은 무한 스트림을 limit 메서드로 제한할 수 있음.

public class StreamExample {
    public static void main(String[] argse) {
        // 스트림 생성의 범위를 5개로 제한
        IntStream ints = new Random().ints().limit(5);
        
        ints.forEach(System.out::println);
    }
}

//출력값
int 범위 내 정수 5개