Wookim

java Stream 최종연산 (3) 본문

programming language/Java

java Stream 최종연산 (3)

개발자인 경우 2022. 1. 21. 17:03

스트림화 된 데이터를 Java의 데이터 형태로 변환

1. 요소의 출력

이전 글에서 stream.forEach() 구문은 사실 최종 연산을 사용하고 있었다.

// 1. 요소의 출력 : forEach()
IntStream.range(1,11).forEach(i -> System.out.print(i + " "));

-- output
-- 1 2 3 4 5 6 7 8 9 10 

 

2. 요소의 소모

reduce는 소모하다라는 뜻이다.

첫번째 인자와 두번째 인자와의 정의한 식을 계산한다.

 

이후 계산 결과와 다음 인자와 같은 연산을 반복하여 최종값을 리턴한다.

 

즉 모든 인자를 소모하고 하나의 결과값을 리턴한다.

int reduce = IntStream.range(1, 11).reduce((i1, i2)->i1 + i2).getAsInt();
System.out.println(reduce);

-- output
-- 55

 

3. 요소의 검색

findFirst는 스트림의 첫번째 요소를 검색하여 리턴한다.

findAny도 마찬가지이나 스트림의 직렬(싱글 스레드) 병렬(멀티 스레드) 처리시 결과가 다르다.

직병렬 방식의 차이에 상관없이 findFirst를 사용하면 항상 첫번째 값을리턴한다.

int findFirst = IntStream.range(1, 11).findFirst().getAsInt();
System.out.println(findFirst);

int findAny = IntStream.range(1, 11).findAny().getAsInt();
System.out.println(findAny);

-- output
-- 1
-- 1

 

4. 요소의 검사

스트림안에 특정 인자의 유무를 확인할 때 주로 사용한다.

boolean anyMatch = IntStream.range(1, 11).anyMatch(i -> i % 2 == 0);
System.out.println(anyMatch);

boolean allMatch = IntStream.range(1, 11).allMatch(i -> i % 2 == 0);
System.out.println(allMatch);

boolean noneMatch = IntStream.range(1, 11).noneMatch(i -> i % 2 == 0);
System.out.println(noneMatch);

-- output
-- true
-- false
-- false

 

5. 요소의 통계

스트림의 통계 연산들이다.

각 연산의 차이점은 min, max 는 Optional 로 결과값을 래핑하여 전달한다.

Long count = IntStream.range(1, 11).count();
System.out.println(count);

OptionalInt optMin = IntStream.range(1, 11).min();
System.out.println(optMin);

int min = IntStream.range(1, 11).min().orElse(-9999);
System.out.println(min);

OptionalInt optMax = IntStream.range(1, 11).max();
System.out.println(optMax);

int max = IntStream.range(1, 11).max().orElse(9999);
System.out.println(max);

-- output
-- 10
-- OptionalInt[1]
-- 1
-- OptionalInt[10]
-- 10

6. 요소의 연산

sum, average는 연산 결과를 optional 로 래핑하는 것에 차이가 있다.

int sum = IntStream.range(1, 11).sum();
System.out.println(sum);

OptionalDouble average = IntStream.range(1, 11).average();
System.out.println(average);

OptionalDouble map = IntStream.range(1, 11).map( i -> i * 2).average();
System.out.println(map);

-- output
-- 55
-- OptionalDouble[5.5]
-- OptionalDouble[11.0]

 

7. 연속된 int 배열 생성

// int 배열 생성
int[] arr =  IntStream.range(1, 11).toArray();

for(int i : arr){
    System.out.print(i + " ");
}

-- output
-- 1 2 3 4 5 6 7 8 9 10

 

8. list 생성

collect 메소드이 인자로 Collectors가 사용된다.

List<Integer> list = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toList());
list.forEach(i -> System.out.print(i + " "));

-- output
-- 1 2 3 4 5

 

9. 맵 생성

list와 마찬가지로 Collectors를 사용한다.

s1->s1 : key,  s1->s1.length() : value 

맵의 형태인 key, value 값을 stream에서 얻어 map을 생성한다.

Map<String, Integer> sMap = Stream.of("i", "am", "wookim", "hello")
        .collect(Collectors.toMap(s1->s1, s1->s1.length()));
for(Map.Entry<String, Integer> e : sMap.entrySet()){
    System.out.println(e.getKey() + " " + e.getValue());
}

-- output
-- wookim 6
-- i 1
-- hello 5
-- am 2

 

reference http://tcpschool.com/java/java_stream_terminal

'programming language > Java' 카테고리의 다른 글

Java Stream 중개 연산 (2)  (0) 2022.01.19
Java Stream(1)  (0) 2022.01.10
Java Stream (0)  (0) 2022.01.10
Spring 예외 처리 패턴  (2) 2022.01.03
spring application 실행 환경 분리 (프로파일)  (0) 2021.07.09
Comments