woowacourse-study/2022-modern-java-in-action

null에 안전한 스트림 생성 방법

Opened this issue · 1 comments

문제

null에 안전한 스트림은 어떻게 생성할까?

선정 배경

null이 될 수 있는 객체로 스트림 만들기를 보고 스트림에서 null처리를 할 수 있는 방법에 대해 간략하게 조사해보았다.

관련 챕터

[5장] 스트림 활용
p.151

Java stream에서 안전한 stream을 생성하여 사용하는 방법

기본적인 stream

Stream 객체로 Stream 생성

Stream chars = Stream.of(”A”, “B”, “C”);

Collection 객체로 Stream 생성

Collection collection = Arrays.asList("A", "B", "C");
collection.steam()
	// 중간연산...
	// 최종연산...
public Stream collectionAsStream(Collection collection) {
	return collection.stream();
}

이렇게 stream을 return할 경우, collection이 비어있을 때 NullPointerException이 발생할 수 있다.

의도되지 않은 null 참조 예외를 방지하려면?

방법 1.

public Stream collectionAsStream(Collection collection) {
	return collection != null ? collection.stream() : Stream.empty();
} // Stream에도 emptyStream()이 있다!

방법 2.

public Stream collectionAsStream(Collection collection) {
	return Optional.ofNullable(collection)
		.map(Collection::stream)
		.orElseGet(Stream::empty);
} // Stream에도 emptyStream()이 있다!

Optional.ofNullbale() - 값이 Null일수도, 아닐수도 있다!

어떤 데이터가 null이 올 수도 있고 아닐 수도 있는 경우에는 Optional.ofNullable로 생성할 수 있다. 그리고 이후에 orElse 또는 orElseGet 메소드를 이용해서 값이 없는 경우라도 안전하게 값을 가져올 수 있다.

// Optional의 value는 값이 있을 수도 있고 null 일 수도 있다.
Optional<String> optional = Optional.ofNullable(getName());
String name = optional.orElse("anonymous");// 값이 없다면 "anonymous" 를 리턴

스트림 내에서 특정 null 값을 빼고 싶다면?

List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull) // null이 아닌 것들만 filter해서 가지고 있도록 할 수 있다
                .collect(Collectors.toList());