[Java] 스트림 생성 (리스트, 배열을 스트림으로, 숫자 범위로부터 스트림, 파일로부터 스트림)

Collection의 Stream 생성


Stream<String> stream = list.stream();
List<String> list = Arrays.asList("kim", "lee", "choo");

 

 

 

 

 

 

배열의 Stream 생성


Arrays의 stream 메소드

Stream<String> stream = Arrays.stream(strArray);
Stream<String> stream = Arrays.stream(new String[] {"kim", "lee", "choo"});

 

Stream의 of 메소드

Stream<String> stream = Stream.of(new String[] {"kim", "lee", "choo"});

// 가변 인자
Stream<String> stream = Stream.of("kim", "lee", "choo");

 

 

 

 

 

숫자 범위로부터 Stream 생성


IntStream의 range 메소드, rangeClosed 메소드를 통해 for 문을 대체할 수 있다.

 

// 1부터 100까지 순차적으로 제공하는 IntStream을 리턴한다.
IntStream stream = IntStream.rangeClosed(1, 100);

// 1부터 99까지 순차적으로 제공하는 IntStream을 리턴한다.
IntStream stream = IntStream.range(1,100);

 

IntStream 대신 자료형에 따라 LongStream, DoubleStream 으로 대체 가능

 

 

 

 

 

 

 

 

 

파일로부터 Stream 생성


//파일의 경로 정보를 가지고 있는 Path 객체 생성
Path path = Paths.get("~~~~/파일명");

//파일의 내용을 lines()로 읽어와서 담음
Stream<String> stream = Files.lines(path, Charset.defaultCharset());

stream.forEach(System.out :: println);

 

 

 

 

 

 

 

 

디렉터리부터 Stream 생성


Path path = Paths.get("~~~~\디렉터리 경로");
Stream<Path> stream = File.list(path);
stream.forEach( p -> System.out.println(p.getFileName()) );