[JAVA] 스트림(Stream)

Jiyeong·2023년 3월 9일
0

JAVA

목록 보기
2/2

문제의 !스트림! 포스팅을 시작해보겠습니다 ㅎㅎ

💭) 자바 공부를 막 시작하고 나서 프로그래머스 level 0 100제를 풀기 시작했는데요,
매번 for - if 남발해서 풀었던 문제가 stream으로 한 줄로 요약 되는 것이 신기하고 부러워서 이거 꼭..포스팅 해야 겠다! 라고 생각했습니다.

스트림이란..

  • 배열, 컬랙션 등의 데이터를 하나씩 참조해서 처리 가능한 기능
  • for문의 사용을 줄여줌
  • [ Stream 생성 - 중개 연산 - 최종 연산 ] 으로 구성됨

1단계 - 스트림 생성

1. 배열 스트림 
String[] arr = new String[]{"a", "b", "c"}
Stream stream = Arrays.stream(arr);


2. 컬랙션 스트림 
ArrayList list = new ArrayList(Arrays.asList(1,2,3,4));
Stream stream = list.strea();

2단계 - 스트림 중개 연산

  • 대표적으로 filtering, mapping이 있습니다. 그 외에도 엄청나게 많아요
1. filtering : 필터링 조건에 참인 요소들만 추출
IntStream intStream = IntStream.range(1,10).filter(n -> n%2 == 0);

2. Mapping : map 안의 연산을 요소별로! 다 수행하는 것
IntStream intStream = IntStream.range(1, 10).map(n->n+1);

3단계 - 스트림 최종 연산

  • 대표적으로 sum(), average() (+ 거의 average는 double형이라서 average().getAsDouble()로 쓰인다), min, max 등이 있습니다.

✨ 스트림 생성 관련 예시

1. 배열 스트림
String[] arr = new String[]{"a", "b", "c"}
Stream stream = Arrays.stream(arr);
stream.forEach(System.out::println);
>>
a
b
c

2. 컬랙션 스트림 
ArrayList list = new ArrayList(Arrays.asList(1,2,3));
Stream stream = list.stream();
stream.forEach(System.in::println);
>>
1
2
3

stream.forEach(num -> System.out.println("num =", num));
>>
num = 1
num = 2
num = 3

3. 스트림 builder -> add로 요소 추가
Stream streamBuilder = Stream.builder().add(1).add(2).add(3).build();
streamBuilder.forEach(System.out::println);
>>
1
2
3

4. 스트림 iterate 
// iterate는 내부 조건을 limit(n)의 n만큼 반복합니다.
// iterate(초기값, 연산).limit(반복횟수)

Stream streamIterate = Stream.iterate(10, n->n*2).limit(3)
streamIterate.forEach(System.out::println)
>>
10
20
40

✨✨ 스트림 중개 연산 예시

1. Filtering
IntStream intStream = IntStream.range(1,10).filter(n -> n%2 == 0);
intStream.forEach(System.in::println);
>>
2
4
6
8


2. Mapping
IntStream intStream = IntStream.range(1, 10).map(n->n+1);
intStream.forEach(n -> System.out.print(n + " ");
>>
2 3 4 5 6 7 8 9 10

3. Sorting
IntStream stream = IntStream.builder().add(5).add(1).add(2).add(8).build();
IntStreamm stream2 = stream.sorted(); //오름차순 정렬
stream2.forEach(System.out::println);
>>
1
2
5
8

✨✨✨ 스트림 최종 연산 예시

1. Sum, Average
int sum = IntStream.range(1,5).sum(); // 1+2+3+4
double average = IntStream.range(1, 5).average().getAsDouble();
System.out.println(sum);
System.out.println(average);
>>
10
2.5

2. Min, Max
int min = IntStream.range(1,5).min().getAsInt();
int max = IntStream.range(1,5).max().getAsInt();
System.out.println(min);
System.out.println(max);
>>
1
4

3. reduce 
Stream<Integer> stream = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)).stream();
System.out.println(stream.reduce((x,y) -> x+y).get()); // (((1+2)+3)+4)+5
>> 
15

+) 예제로 실전 감각 익혀보기!

문제 ) 1-10 숫자 중 짝수들의 합을 구하시오.

int sum = IntStream.range(1,11).filter(n->n%2==0).sum()
System.out.println(sum);
>> 
30
profile
Drill처럼 파고들자 🔥

0개의 댓글