JAVA - 람다와 스트림(7)

jodbsgh·2022년 4월 30일
0

💡"JAVA"

목록 보기
60/67

스트림 만들기 - 컬렉션

  • Collection 인터페이스의 stream()으로 컬렉션을 스트림으로 변환
ex) Stream<E> stream()	//Collection 인터페이스의 메서드

List<Integer> list = Array.asList(1,2,3,4,5);
Stream<Integer> intStream = list.stream();	//list를 스트림으로 변환

//스트림의 모든 요소를 출력
intStream.forEach(System.out::print);	//12345
intStream.forEach(System.out::print);	//에러, 스트림이 이미 닫혔다.

스트림 만들기 - 배열

  • 객체 배열로부터 스트림 생성하기
ex)
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)

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.stream(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 startInclusiv, int endExclusive)

스트림 만들기 - 임의의 수

  • 난수를 요소로 갖는 스트림 생성하기
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(lng 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)
IntStream intStream = IntStream.range(1,5);		//1,2,3,4
IntStream intStream = IntStream.rangeClosed(1,5); //1,2,3,4,5

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

  • 람다식을 소스로 하는 스트림 생성하기
static<T> Stream<T> iterate(T seed, UnaryOperator<T> f)	//이전 요소에 종속적
static<T> Stream<T> generate(Supplier<T> s)				//이전 요소에 독립적
  • 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);

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

  • 파일을 소스로 하는 스트림 생성하기
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
profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글