-
[JAVA] stream자바 2023. 4. 23. 17:44
1) inputstream / outputstream
- stream : 파일을 읽거나 쓸 때 네트워크 소켓을 거쳐 통신할 때 쓰이는 추상적인 개념
- byte : 데이터는 0이나 1로 귀결되고 0이나 1이 8개 모이면 byte
- inputStream / outputStream : 단일 방향, 연속적으로 흘러간다. 추상 클래스이며 추상 메서드를 오버라이딩해서 다양한 역할을 수행할 수 있다. (파일/네트워크/메모리 입출력)
- 프로그램이 네트워크 상 다른 프로그램과 데이터를 교환하기 위해서는 양쪽 모두 입력 스트림과 출력 스트림이 필요
- 프로그램이 출발지/도착지인지에 따라 스트림의 종류가 결정
1-1) inputstream : byte 기반 입력 스트림의 최상위 추상클래스, 파일 데이터를 읽거나 네트워크 소켓을 통해 데이터를 읽거나 키보드에서 입력한 데이터를 읽을 때 사용
> 데이터 읽기
> 특정 시점으로 되돌아가기
> 얼마나 데이터가 남았는지 보여주기
> 통로 끊기
1-2) outputStream : 바이트 기반 출력 스트림의 최상위 추상클래스
2) bufferedreader - lines() > 읽은 텍스트 줄의 스트림을 가져오는 방법
> public Stream<String> lines()
Returns a Stream, the elements of which are lines read from this BufferedReader. The Stream is lazily populated, i.e., read only occurs during the terminal stream operation.
The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.
If an IOException is thrown when accessing the underlying BufferedReader, it is wrapped in an UncheckedIOException which will be thrown from the Stream method that caused the read to take place. This method will return a Stream if invoked on a BufferedReader that is closed. Any operation on that stream that requires reading from the BufferedReader after it is closed, will cause an UncheckedIOException to be thrown.
Returns: a Stream<String> providing the lines of text described by this BufferedReader
4) stream.reduce (커스텀 집계)
- 스트림은 기본 집계 메서드인 sum(), average(), count(), max(), min()을 제공하지만, 프로그램화해서 다양한 집계 결과물을 만들 수 있도록 reduce() 메서드도 제공한다.
- 정의된 연산이 아닌 개발자가 직접 구현한 연산을 적용한다.
- 최종 연산으로 스트림의 요소를 소모하며 연산을 수행한다.
5) 자바의 람다식
람다 : 익명의 함수를 지칭하는 용어로 함수를 보다 단순하게 표현하는 방법
- 장점 : 코드의 간결성, 자연연산 수행, 병렬처리 가능
- 단점 : 람다식 호출이 까다로움, 람다 stream 사용 시 단순 for문 혹은 while문 사용보다 성능 떨어짐,
가독성을 오히러 떨어뜨릴 수 있음
- 표현식 :
( 매개변수... ) -> { 실행문 }
( ) -> 1
( ) -> {return 1;}
(참고)
https://ho-log.tistory.com/128
https://ict-nroo.tistory.com/43
https://dongminkim94.tistory.com/60
https://lannstark.tistory.com/34
https://bamdule.tistory.com/179
https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html
https://www.techiedelight.com/ko/how-to-read-a-file-using-bufferedreader-in-java/
https://cornswrold.tistory.com/544
728x90'자바' 카테고리의 다른 글
[JAVA] Static 키워드 (0) 2023.04.27 [JAVA] openAI API 이용한 chatGPT, 자바로 채팅 기능 구현하기 - V2 (0) 2023.04.24 [자바] URLConnection, HTTPURLConnection (0) 2023.04.22 [JAVA] openAI API 이용한 chatGPT, 자바로 채팅 기능 구현하기 - V1 (0) 2023.04.21 인프런 예제로 공부하는 Java 100 문제풀이 Part.2 (0) 2022.12.26