관리 메뉴

IT.FARMER

java null safe stream 생성 방법 본문

JAVA

java null safe stream 생성 방법

아이티.파머 2019. 9. 5. 13:40
반응형

java stream 에서 안전한 stream 을 생성 하여 사용 하는 방법에 대해 알아보자 .

해당 내용을 이해하기 위해서는 
우선적으로 java8의 method refreences, Lamabda Expressions, Optional 등 
Stream 에대한 기본인 방법에 익숙해야 한다.


기본적으로 Stream 만들기 
Stream 객체로 Stream 생성

 Stream charStream = Stream.of("A","B","C"); 


Collection 객체로 Stream 생성 

 Collection collection = Arrays.asList("A","B","C"); 
 collection.stream(); 

  
우리는 대게 Stream 을 사용할때 다음과 같이 사용한다.
이때 Null 을 가르키는 경우 NullPointException이 발생될수 있다. 

public Stream collectionAsStream(Collection collection) { 
	return collection.stream(); 
} 

   
의도되지 않는 Null의 참조 예외를 방지하기 위해 Null 검사를 마지막에 수행할 수 있다.

 public Stream collectionAsStream(Collection collection) { 
	return collection != null ?  collection.stream() : Stream.empty(); 
} 


java8의 Optional 을 이용하여 검사를 추가 할수 있다. 

public Stream collectionToStream(Collection collection) { 
  return Optional.ofNullable(collection) 
  .map(Collection::stream) 
  .orElseGet(Stream::empty); 
} 

 

반응형

'JAVA' 카테고리의 다른 글

Intellij 2019.2 build tool gradle default  (0) 2019.11.07
java excle 대용량 다운로드 poi  (0) 2019.09.19
병렬처리와 동시성  (0) 2019.05.27
CompletableFuture  (0) 2019.05.16
API call back off time(재요청 타시간)  (0) 2019.05.07