당신이 알아야 할 것들의 증가 속도는 당신이 아는 것들의 증가 속도보다 크다
  • 🌈고용 노동자의 소양 : 기여, 보상 그리고 뻔뻔함
  • LLM에게 좌뇌를
  • Going to AI
  • 세대론 유감
  • LIST
    • 어쩌다, 애자일스러움
    • Graph Databases - 올 것은 온다
    • Software Composability in Crypto
    • The Next Decade in AI: Four Steps Towards Robust Artificial Intelligence
    • AI 에듀테크 - 교육절벽은 없다?
    • The Design of Decisions
    • How Modern Game Theory is Influencing Multi-Agent Reinforcement Learning Systems
    • 블록체인과 콘텐츠의 왕국 (작성중)
    • How to grow a mind: statistics, structure, and abstraction [paper]
  • Text
    • 코딩, 몇살까지
    • '타다'가 드러낸 한국 4대 빅이슈
    • [딴지일보]MMORPG적 세계관과 능력주의자라는 환상
    • #n
    • 장면들
  • 임시
    • PAGE
      • 마이크로서비스 아키텍처
      • SHACL
      • IPLD / Multiformats
      • MPC
      • Semantic BlockChain
      • Java Stream
      • 인공지능과 교육
      • [scrap] The Future of Data: A Decentralized Graph Database
      • DAG - 방향성 비순환 그래프(Directed Acyclic Graph)
      • Untitled
Powered by GitBook
On this page
  • Stream - 생성 / 가공 / Terminal Operations
  • ** Null-safe
  • 불변 컬렉션

Was this helpful?

  1. 임시
  2. PAGE

Java Stream

PreviousSemantic BlockChainNext인공지능과 교육

Last updated 1 year ago

Was this helpful?

Stream - 생성 / 가공 / Terminal Operations

  • 배열과 컬렉션을 함수형으로 처리할 수 있다

  • 병렬처리(multi-threading)가 가능하다

  • 재사용은 불가능하다

** 생성

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream(); // 병렬 처리 스트림

Stream.iterate()

Stream<Integer> iteratedStream = 
  Stream.iterate(30, n -> n + 2).limit(5); // [30, 32, 34, 36, 38]

** 가공 (중개 연산)

List<String> names = Arrays.asList("Eric", "Elena", "Java");

filter, map

flatmap

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
List<List<String>> list = 
  Arrays.asList(Arrays.asList("a"), 
                Arrays.asList("b"));  // [[a], [b]]
                
                
List<String> flatList = 
  list.stream()
  .flatMap(Collection::stream)
  .collect(Collectors.toList());   // [a, b]
  
  
// if students  
students.stream()
  .flatMapToInt(student -> 
                IntStream.of(student.getKor(), 
                             student.getEng(), 
                             student.getMath()))
  .average().ifPresent(avg -> 
                       System.out.println(Math.round(avg * 10)/10.0));  
                

peek

// Stream<T> peek(Consumer<? super T> action);

int sum = IntStream.of(1, 3, 5, 7, 9)
  .peek(System.out::println) // 1, 3, 5, 7, 9
  .sum();  // sun = 25

** Terminal Operations (최종 연산)

reduce, collect

** Null-safe

public <T> Stream<T> collectionToStream(Collection<T> collection) {
    return Optional
      .ofNullable(collection)
      .map(Collection::stream)
      .orElseGet(Stream::empty);
  }
  
  
List<String> nullList = null;

nullList.stream()
  .filter(str -> str.contains("a"))
  .map(String::length)
  .forEach(System.out::println); // NPE!


collectionToStream(nullList)
  .filter(str -> str.contains("a"))
  .map(String::length)
  .forEach(System.out::println); // []

불변 컬렉션

Guava는 불변 리스트 생성을 위 팩토리 메서드나 빌더 클래스를 제공합니다.

import com.google.common.collect.ImmutableList;

List<String> fruits = ImmutableList.of("Apple", "Banana", "Cherry");

fruits.add("Lemon"); // UnsupportedOperationException
  • Java 9 에서는 of 메소드 제공

Java 스트림 Stream (1) 총정리 | Eric Han's IT BlogEric Han's IT Blog
Logo