티스토리 뷰

Java

[Stream API] 스트림 중간연산 (3/3)

GOMSHIKI 2023. 11. 21. 20:24

 

 

1. Stream<T[ ]>를 Stream<T>로 변환 - flatMap()

스트림 요소가 배열 혹은 map() 연산 결과가 배열인 경우, map() 보단 flatmap()으로 다루는 걸 더 추천

 

 

 

* 아래 예시코드와 같이 별도로 있는 존재하는 문자열 배열을 하나의 배열로 받고 싶다면 flatMap을 이용하면 됨

// 예시코드 1)
Stream<String[]> strmArryStrm = Stream.of(
                                   new String[]{"abc", "def", "ghi"},
                                   new String[]{"ABC", "GHI", "JKLMN"}
                                );

// map 사용 시 반환 타입 :        Stream<String[]> -> Stream<Stream<String>>
Stream<Stream<String>> strStrStrm = strmArryStrm.map(Arrays::stream);

// flatmap 사용 시 반환 타입 :    Stream<String[]> -> Stream<String>
Stream<String> stringStream = strmArryStrm.flatMap(Arrays::stream);


// 예시코드 2) 두 스트림 합치기
Stream<String> strStrm = Stream.of("abc", "def", "jklmn");
Stream<String> strStrm2 = Stream.of("ABC", "GHI", "JKLMN");

// 위 두 스트림을 하나의 스트림으로 묶음
Stream<Stream<String>> strmStrm = Stream.of(strStrm, strStrm2);

// 문자열 배열 변환 후 문자열로 변환
Stream<String> strStream = strmStrm
                    .map(s->s.toArray(String[]::new)) // Stream<String[]>
                    .flatMap(Arrays::stream); // Stream<String>

 

 

 

2. Optional<T> 

2-1. 참조변수가 null일 가능성이 있는경우 및 초기화할 때- ofNullable(), empty()

객체에 담아 반환하는 경우, 반환 결과가 null인 경우 if 문을 쓰지 않고 Optional로 간단히 처리할 수 있음
public final class Optional<T> {

	private final T value;  // T타입의 참조변수
    
}

// 예시 코드
String str = "abc";
Optional<String> optVal = Optional.of(str);
Optional<String> optVal = Optional.of("abc");
Optional<String> optVal = Optional.of(new String("abc"));


// 1) 참조변수의 값이 null 일 가능성이 있다면 : ofNullabe() 
Optional<String> optVal = Optional.of(null); // NullPointException 발생
Optional<String> optVal = Optional.ofNullable(null) // 예외발생 X


// 2) empty()로 초기화
Optional<String> optVal = null;
Optional<String> optVal = Optional.<String>empty(); // 빈 객체로 초기화

 

 

 

2-2. Optional 객체 가져오기 - get(), orElse(), orElseGet(), orElseThrow()

Optional 객체에 저장된 값 가져올 때 : get()
값이 null일 경우 : orElse()
null 을 대체할 값을 반환(람다식) : orElseGet()
null 일 경우 예외 발생시키고 싶을 때 : orElseThrow()
// 예시코드 : get(), orElse()
Optional<String> optVal = Optional.of("abc");
String str1 = optVal.get();        // 가지고 있는 값이 null 일 경우 예외발생
String str2 = optVal.orElse("");   // 가지고 있는 값이 null 일 경우, "" 반환

// 예시코드 : orElseGet(), orElseThrow()
T orElseGet(Supplier<? extends T> other)
T orElseThrow(NullPointException::new)

String str3 = optVal2.orElseGet(String::new);
String str4 = optVal2.orElseThrow(NullPointException::new);


// 사용 예시
int result = Optional.of("123")
                .filter(x->x.length() > 0)
                .map(Integer::parseInt).orElse(-1);
                
 
result = Optional.of("")
            .filter(x->x.length() > 0)
            .map(Integer::parseInt).orElse(-1);

 

 

 

2-3. Optional 값이 null 이면 false, 아니면 true 반환 - isPresent()

// 예시코드
if(Optional.ofNullable(str).isPresent()){
	System.out.println(str);
}

 

 

2-4. 값이 있으면 주어진 람다식 실행, 없으면 아무것도 안함 - ifPresent()

ifPresent() 는 Optional<T>를 반환하는 findAny(), findFirst() 같은 최종연산과 조합해 사용하면 좋음
Optional<T> findAny()
Optional<T> findFirst()
Optional<T> max(Comparator<? super T> comparator)
Optional<T> min(Comparator<? super T> comparator)
Optional<T> reduce(BinaryOperator<T> accumlator)
// 예시코드
Optional.ofNullable(str).ifPresent(System.out::println);

 

 

2-5. 기본형 스트림에도 적용가능 - OptionalInt, OptionalLong, OptionlDouble

OptionalInt    findAny()
OptionalInt    findFirst()
OptionalInt    reduce(IntBinaryOperator op)
OptionalInt    max()
OptionalInt    min()
OptionalDouble average()

 

Optional 클래스 값을 반환하는 메서드
Optional<T> T get()
OptionalInt int getAsInt()
OptionalLong long getAsLong()
OptionalDouble double getAsDouble()
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함