Java Stream

이승현·2022년 9월 26일
0

1. Stream이란?

  • 자료의 입출력을 도와주는 중간매개체
  • 입력과 출력이 관련된 곳이면 어디서든 동작
  • 스트림은 외부에서 들어오는 데이터를 입력받고(input) 출력(out)하는 '터널'과 같은 중간자 역할을 수행
  • 중요한 점은 '단방향'으로 데이터를 송수신 하기 때문에 Input과 Output을 구분하여 사용

<입력 Stream>
(1) 데이터를 먼저 Stream으로 읽어 들임
(2) Stream에 존재하는 데이터를 하나씩 읽어 들일 수 있음

<출력 Stream>
(1) 출력 Stream으로 데이터를 보냄
(2) 보낸 데이터를 비워 버림
(3) 출력 Stream에 존재하던 데이터가 모두 목표지점에 저장됨

-->
(1) 목표로 하는 데이터를 정함
(2) 데이터에 맞는 Stream 생성
(3) Stream class의 멤버 메소드를 이용하여 쉽게 데이터를 핸들(기록하고 읽어들이거나, 보내거나 받거나)

2.Stream의 종류

  • 문자 단위 Stream
  • Byte 단위 Stream

<문자 Stream의 구성도>

Reader : 입력 문자 Stream
Writer : 출력 문자 Stream


<Byte Stream의 구성도>

InputStream : 입력 Byte Stream
OutputStream : 출력 Byte Stream



Path.toAbsolutePath()

상대 경로를 절대 경로로 변환하는 메서드

Stream을 이용하여 람다함수형식으로 간결하고 깔끔하게 요소들의 처리가 가능

배열의 원소를 가공하는데 있어 map, filter, sorted가 있음

1. map

요소들을 특정조건에 해당하는 값으로 변환해줌
요소들을 대, 소문자 변형 등의 작업을 하고 싶을 때 사용 가능

2. filter

요소들을 조건에 따라 걸러내는 작업
길이의 제한, 특정 문자 포함등의 작업을 하고 싶을 때 사용 가능

3. sorted

요소들을 정렬해주는 작업

요소들의 가공이 끝났다면 리턴해줄 결과를 collect를 통해 만들어줌

예시)
ArrayList<string> list = new ArrayList<>(Arrays.asList("Apple","Banana","Melon","Grape","Strawberry"));

System.out.println(list);

//[Apple, Banana, Melon, Grape, Strawberry]

1) map
list.stream().map(s->s.toUpperCase());
list.stream().map(String::toUpperCase);
list.stream().map(String::toUpperCase).forEach(s -> System.out.println(s));
//APPLE
//BANANA
//MELON
//GRAPE
//STRAWBERRY

2) filter
list.stream().filter(t->t.length()>5)
System.out.println(list.stream().filter(t->t.length()>5).collect(Collectors.joining(" "))); //Banana Strawberry

System.out.println(list.stream().filter(t->t.length()>5).collect(Collectors.toList())); //[Banana, Strawberry]


3) sorted
list.stream().sorted()
System.out.println(list.stream().sorted().collect(Collectors.toList())); //[Apple, Banana, Grape, Melon, Strawberry] 

0개의 댓글