[자바의 정석] 14. 람다와 스트림 - 스트림 만들기

jyleever·2022년 10월 3일
0

자바의 정석

목록 보기
9/12
post-thumbnail

스트림 만들기 - 컬렉션

Collection 인터페이스의 stream()으로 컬렉션을 스트림으로 변환

Stream<E> stream() // Collection 인터페이스의 메서드
List<Integer> list = Arrays.asList(1,2,3,4,5);
Stream<Integer> intStream = list.stream(); // list를 스트림으로 변환

// 스트림의 모든 요소를 출력
intStream.forEach(System.out::print); // 12345
intStream.forEach(System.out::print); // 에러; 스트림이 이미 닫힘
  • forEach와 같은 최종 연산은 1번 실행하고 나면 스트림이 닫히므로 같은 스트림에 대해 1번만 연산 가능
  • 스트림을 또 생성해야 연산 가능

스트림 만들기 - 배열

객체 배열로부터 스트림 생성하기

Stream<T> Stream.of(T... values) // 가변 인자
Stream<T> Stream.of(T[])
Stream<T> Arrays.stream(T[])
Stream<T> Arrays.stream(T[] array, int startInclusive, int endExclusive) // 3, 8 이라면 3, 4, 5, 6, 7 까지
Stream<String> strStream = Stream.of("a", "b", "c"); // 가변 인자
Stream<String> strStream = Stream.of(new String[]{"a", "b", "c"});
Stream<String> strStream = Arrays.stream(new String[]{"a", "b", "c"});
Stream<String> strStream = Arrays.steram(new String[]{"a", "b", "c"}, 0, 3);

기본형 배열로부터 스트림 생성하기

IntStream IntStream.of(int ... values) // Stream이 아니라 IntStream
IntStream IntStream.of(int[])
IntStream Arrays.stream(int[])
IntStream Arrays.stream(int[] array, int startInclusive, int endExclusive)

Stream.ofArrays.stream 중에 편한 것을 사용하면 된다.

IntStream vs Stream<Integer>

int[] intArr = {1,2,3,4,5};
IntStream intStream = Arrays.stream(intArr);
intStream.forEach(System.out::println);
Integer[] intArr = {new Integer(1), new Integer(2), ...}; 으로작성해야 하지만
Integer[] intArr = {1,2,3,4,5}; 라고 작성해도 자동으로 autoboxing돼서 Integer 객체 별로 됨
Stream<Integer> intStream = Arrays.stream(intArr);
intStream.forEach(System.out::println);

IntStream

  • IntStream은 int 기본형
    IntStream은 int 형인 것을 알고 있기 때문에 count, sum, average 등의 메서드를 제공한다.

Stream<T>

  • Stream<Integer>은 Integer
    Stream<Integer>은 객체 Stream이기 때문에 SUsum, average 등을 제공하지 않음

    Stream<T>는 숫자 외에도 여러 타입의 스트림이 가능해야 하므로 숫자 스트림에만 사용할 수 있는 sum(), average()를 넣지 않음

스트림 만들기 - 임의의 수(난수)

난수를 요소로 갖는 스트림 생성하기

IntStream intStream = new Random().ints(); // 무한 스트림 생성
IntStream.limit(5).forEach(System.out::println) // 5개의 요소만 출력
IntStream intStream = new Random().ints(5); // 크기가 5인 난수 스트림을 반환 (범위 지정 가능)
Integer.MIN_VALUE <= ints() <= Integer.MAX_VALUE
Long MIN_VALUE <= longs() <= Long.MAX_VALUE
0.0 <= doubles() < 1.0

지정된 범위의 난수를 요소로 갖는 스트림을 생성하는 메서드(Random 클래스)

> 무한 스트림
IntStream ints(int begin, int end)
LongStream longs(long begin, long end)
DoubleStream doubles(double begin, double end) // 무한 스트림

> 유한 스트림
IntStream ints(long streamSize, int begin, int end)
LongStream longs(long streamSize, long begin, long end)
DoubleStream doubles(long streamSize, double begin, double end)

스트림 만들기 - 특정 범위의 정수

특정 범위의 정수를 요소로 갖는 스트림 생성하기(IntStream, LongStream)

IntStream IntStream.range(int begin, int end)
IntStream IntStream.rangeClosed(int begin, int end); // end가 포함됨
IntStream intStream = IntStream.range(1, 5); // 1,2,3,4
IntStream intStream = IntStream.rangeClosed(1, 5); // 1,2,3,4,5

스트림 만들기 - 람다식 iterate(), generate()

람다식을 소스로 하는 스트림 생성하기

  • iterate(T seed, UnaryOperator f) // 단항 연산자
  • `generate(Supplier s) 주기만 하는 것 입력 X, 출력 O
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) // 이전 요소에 종속적
// seed : 초기값, UnaryOperator<T> 무한 스트림
static <T> Stream<T> generate(Supplier<T> a) // 이전 요소에 독립적

Iterate()는 이전 요소를 seed로 해서 다음 요소를 계산한다
초기값을 가지고 있기 때문에 이전 값과 관련이 있음

Stream<Integer> evenStream = Stream.iterate(0, n -> n+2) // 0, 2, 4, 6, ...

generate()는 seed를 사용하지 않는다
초기값을 사용하지 않고 이전 값과 관련이 없다

Stream<Double> randomStream = Stream.generate(Math::random);
Stream<Integer> oneStream = Stream.generate(() -> 1); // 계속 1만 나옴

스트림 만들기 - 파일과 빈 스트림

파일을 소스로 하는 스트림 생성하기

Stream<Path> Files.list(Path dir) // Path는 파일 또는 디렉토리
Stream<String> Files.lines(Path path) // 파일 내용을 라인 단위로 읽음
Stream<String> Files.lines(Path path, Charset cs)
Stream<String> lines() // BufferedReader 클래스(파일의 내용 읽을 때 편리...)의 메서드

비어있는 스트림 생성하기

Stream emptyStream = Stream.empty(); // empty()는 빈 스트림을 생성해서 반환한다
long count = emptyStream.count(); // count의 값은 0

0개의 댓글