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