SlideShare a Scribd company logo
1 of 26
Download to read offline
Java 8 Stream API 
A differentway to process collections 
09:18:24
09:19:27 
HTTP://starplatina.tistory.com 
dosajun@gmail.com 
@sleepJune 
김제준
나즈혼 
람다 
기본메서드 
STREAM API 
날짜API 
동시성개선 
Base 64 
메타프로그래밍향상 
자바스크립트엔진 
2014.3현재버전8.25 09:18:25
ListtransactionIds =newArrayList(); 
for(Transactiont :groceryTransactions) { 
transactionIds.add(t.getId()); 
} 
Collections.sort(groceryTransactions, newComparator() { 
publicintcompare(Transactiont1, Transactiont2) { 
returnt2.getValue().compareTo(t1.getValue()); 
} 
}); 
ListgroceryTransactions =newArrayList(); 
for(Transactiont :groceryTransactions) { 
if(t.getType() ==Transaction.GROCERY) { 
groceryTransactions.add(t); 
} 
} 
Java 코드로구매내역구하기 
식료품점에서구매한걸찾고 
사용금액순으로정렬한뒤 
거래내역의ID를추출 
09:18:25
그럼Database에서는? 
SELECT id FROM TRANSACTIONS 
WHERE type = ‘GROCERY’ ORDER BYvalue DESC 
별도의작업없이이미등록된집계함수를사용 
SUM, MAX, COUNT, AVG등등 
09:18:25
ListgroceryTransactions =newArrayList(); 
for(Transactiont :groceryTransactions) { 
if(t.getType() ==Transaction.GROCERY) { 
groceryTransactions.add(t); 
} 
} 
Collections.sort(groceryTransactions, newComparator() { 
publicintcompare(Transactiont1, Transactiont2) { 
returnt2.getValue().compareTo(t1.getValue()); 
} 
}); 
ListtransactionIds =newArrayList(); 
for(Transactiont :groceryTransactions) { 
transactionIds.add(t.getId()); 
} 
다시한번자바코드 
길다! 
복잡하다! 
코딩해야된다! 
09:18:25
그래서준비했습니다! 
ListtransactionsIds =transactions.stream() 
.filter(t ->t.getType() ==Transaction.GROCERY) 
.sorted(Comparator.comparing(Transaction::getValue).reversed()) 
.map(Transaction::getId) 
.collect(Collectors.toList()); 
람다표현식 
메소드참조 
09:18:25
일반적인스트림의흐름 
filter 
sorted 
map 
collect 
transactions 
2.중간작업(Intermediate Operations) 
PipeLine 
1. 데이터소스 
3. 종료작업(Terminal Operations) 
09:18:25
중간작업및종료작업 
중간작업(Intermediate Operations) 
•항상스트림을리턴 
•Pipeline 형태로연결시킬수잇음 
•데이터를처리하기위한로직 
•직접처리를시작할수는없음 
•오브젝트를리턴하거나, collection 또는void 리턴가능 
•Pipeline으로구성된작업을시작 
•한번수행되고난후에작업한스트림에재작업불가능 
종료작업(Terminal Operations) 
flatMap 
map 
distinct 
sorted 
limit 
peek 
filter 
foreach 
skip 
toArray 
reduce 
collect 
minmax 
count 
anyMatch 
allMatchnoneMatch 
firstFind 
anyFind 
09:18:25
좀더상세히 
Id : 1 
Value : 100 
Id : 3 
Value : 80 
Id : 6 
Value : 120 
Id : 10 
Value : 50 
Id : 7 
Value : 40 
Stream <Transaction) 
Id : 3 
Value : 80 
Id : 6 
Value : 120 
Id : 10 
Value : 50 
.filter(t ->t.getType() 
==Transaction.GROCERY) 
Stream <Transaction) 
Id : 6 
Value : 120 
Id : 3 
Value : 80 
Id : 10 
Value : 50 
.sorted( 
Comparator.comparing( 
Transaction::getValue).reversed()) 
Stream <Transaction) 
6 
3 
10 
.map(Transaction::getId) 
Stream <Integer) 
6 
3 
10 
.collect(Collectors.toList()); 
List<Integer) 
09:18:25
Stream API 
•Java.util.stream 
•연산의선언적서술 
•반복구조캡슐화, 알고리듬분리 
•제어흐름추상화 
•함수형방식처리: 데이터불변 
•지연처리, 대부분의작업을단일반복수행으로처리 
•무한연속데이터흐름API 
•다양한데이터원천지원: 컬렉션, 생성메서드, 파일I/O 등 
09:18:25
컬렉션과스트림 
스트림 
컬렉션 
List 
Map 
Set 
보관형자료구조 
데이터처리추상화 
09:18:25
스트림과컬렉션처리방법의차이 
•파이프라이닝(Pipelining) 
•많은스트림의기능들이스트림자기자신을리턴 
•처리작업이체인처럼연결되어큰파이프라인처럼동작하도록함 
•내부반복(Internal Iteration) 
•명시적으로반복작업을수행해야되는컬렉션과달리스트림작업은내부에서처리 
09:18:25
잠시중간정리 
1.질의를할데이터소스(Collection 같은)가필요 
2.파이프라인을형성하는중간작업(Intermediate Operations) 
3.파이프라인을실행하고결과를리턴하는종료작업(Terminal Operations) 
Stream 을사용하는일반적인3가지내용 
09:18:25
java.util.stream 
•Building Streams 
•Infinite Streams 
•Numeric Streams 
•Filtering 
•Mapping 
•Finding and matching 
•Reducing 
•Collect 
09:18:25
Building Streams 
Stream<Integer>numbersFromValues =Stream.of(1, 2, 3, 4); 
int[] numbers ={1, 2, 3, 4}; 
IntStreamnumbersFromArray =Arrays.stream(numbers); 
longnumberOfLines =Files.lines( 
Paths.get(“yourFile.txt”), Charset.defaultCharset()) 
.count(); 
Collection, 숫자들, 값목록, 배열, 파일 
값목록, 배열에서Stream 생성 
파일에서Stream 생성 
09:18:25
Infinite Streams 
Stream<Integer>numbers =Stream.iterate(0, n ->n +10); 
numbers.limit(5).forEach(System.out::println); 
// 0, 10, 20, 30, 40 
Stream.iterate 
Stream.generate 
09:18:25
Numeric Streams 
intstatement =transactions.stream() 
.map(Transaction::getValue) 
.sum(); // error since Stream has no sum method 
intstatementSum =transactions.stream() 
.mapToInt(Transaction::getValue) 
.sum(); // works! 
IntStream 
DoubleStream 
LongStream 
mapToInt 
mapToDouble 
mapToLong 
sum(), min(), max(), average(), count() 
intstatementSum =transactions.stream() 
.mapToInt(Transaction::getValue) 
.IntSummaryStatistics(); 
// IntSummaryStatistics{count=7, sum=28, min=1, average=4.000000, max=7} 
09:18:25
Filtering 
•filter 
•주어진predicate와일치하는stream을리턴 
•distinct 
•중복을제거한유니크엘리먼트stream을리턴 
•limit(n) 
•주어진사이즈(n) 까지의stream을리턴 
•skip(n) 
•주어진엘리먼트길이까지제외한stream을리턴 
09:18:25
Mapping 
List<String>words =Arrays.asList("Oracle", "Java", "Magazine"); 
List<Integer>wordLengths =words.stream() 
.map(String::length) 
.collect(toList()); 
map(String::length) 인자로전달받은값들을가지고새로운Stream 생성 
List에저장된단어들의길이를가지고있는새로운list 생성 
map(e -> e * 2) 
map(s -> s.toUpperCase()) 
09:18:25
Finding and Matching 
transactions.stream() 
.filter(t ->t.getType() ==Transaction.GROCERY) 
.findAny() 
.ifPresent(System.out::println); 
booleanexpensive =transactions.stream() 
.allMatch(t->t.getValue() >100); 
anyMatch, allMatch, noneMatch 
Optional<Transaction>=transactions.stream() 
.filter(t ->t.getType() ==Transaction.GROCERY) 
.findAny(); 
findFirst, findAny 
java.util.Optional 
09:18:25
Reducing 
intsum =0; 
for(intx :numbers) { sum +=x; } 
intsum =numbers.stream().reduce(0, (a, b) ->a +b); 
intproduct =numbers.stream().reduce(1, (a, b) ->a *b); 
intproduct =numbers.stream().reduce(1, Integer::max); 
for loop 를활용한덧셈 
초기화값: 0 
BinaryOperator<T> : 두개의엘리멘트를더해새로운값을생성 
모든값을곱하기 
최대값구하기 
엘리먼트들을하나의결과로추출 
09:18:25
Collect 
09:18:25 
List<Person>filtered =persons 
.stream() 
.filter(p ->p.name.startsWith("P")) 
.collect(Collectors.toList());// Collectors.toSet() 
System.out.println(filtered); // [Peter, Pamela] 
Map<Integer, List<Person>>personsByAge =persons 
.stream() 
.collect(Collectors.groupingBy(p ->p.age)); 
personsByAge 
.forEach((age, p) ->System.out.format("age %s: %sn", age, p)); 
// age 18: [Max]// age 23: [Peter, Pamela]// age 12: [David]
정리 
1.Stream API 의다양한기능을활용해데이터처리를최적화할수있다. 
2.람다와메서드참조를알아두면더좋음! 
3.병렬처리를손쉽게지원 
•stream() -> parallelStream() 
09:18:25
참고자료 
1.Processing Data with Java SE 8 Streams 
•http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html 
2.Beyond Java : 자바8을중심으로본자바의혁신 
•http://www.slideshare.net/gyumee/beyond-java-8 
3.java.util.stream 
•https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
THANKYOU! 
09:18:25

More Related Content

What's hot

Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseSOAT
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8Alex Tumanoff
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing TipsShingo Furuyama
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 

What's hot (20)

The STL
The STLThe STL
The STL
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Swift internals
Swift internalsSwift internals
Swift internals
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entreprise
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing Tips
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 

Viewers also liked

자바8 스트림 API 소개
자바8 스트림 API 소개자바8 스트림 API 소개
자바8 스트림 API 소개beom kyun choi
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰Sungchul Park
 
씹고 뜯고 맛보고 즐기는 스트림 API
씹고 뜯고 맛보고 즐기는 스트림 API씹고 뜯고 맛보고 즐기는 스트림 API
씹고 뜯고 맛보고 즐기는 스트림 APIArawn Park
 
자바8 람다식 소개
자바8 람다식 소개자바8 람다식 소개
자바8 람다식 소개beom kyun choi
 
keras 빨리 훑어보기(intro)
keras 빨리 훑어보기(intro)keras 빨리 훑어보기(intro)
keras 빨리 훑어보기(intro)beom kyun choi
 
Java 자료구조 비교 (Java1.6 기준)
Java 자료구조 비교 (Java1.6 기준)Java 자료구조 비교 (Java1.6 기준)
Java 자료구조 비교 (Java1.6 기준)혜웅 박
 
혼자 있고 싶은 순간 코쿵! (Cocoong)
혼자 있고 싶은 순간 코쿵! (Cocoong)혼자 있고 싶은 순간 코쿵! (Cocoong)
혼자 있고 싶은 순간 코쿵! (Cocoong)ksyeah
 
1. introduction to java8
1. introduction to java81. introduction to java8
1. introduction to java8흥래 김
 
자라나는 소프트웨어
자라나는 소프트웨어자라나는 소프트웨어
자라나는 소프트웨어jongbhin
 
[강의소개] 안드로이드 앱 개발 입문 캠프 4기
[강의소개] 안드로이드 앱 개발 입문 캠프 4기[강의소개] 안드로이드 앱 개발 입문 캠프 4기
[강의소개] 안드로이드 앱 개발 입문 캠프 4기FAST CAMPUS
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
5. 이모셔널 디자인
5. 이모셔널 디자인5. 이모셔널 디자인
5. 이모셔널 디자인Suyeong Park
 
Git 더하기 GitHub(Git클라이언트 활용) / Getting started with git+github
Git 더하기 GitHub(Git클라이언트 활용) / Getting started with git+githubGit 더하기 GitHub(Git클라이언트 활용) / Getting started with git+github
Git 더하기 GitHub(Git클라이언트 활용) / Getting started with git+githubJunyoung Lee
 
2014 HTML5 총정리
2014 HTML5 총정리2014 HTML5 총정리
2014 HTML5 총정리Wonsuk Lee
 
2013년 html5 총정리 (Summary of HTML5 Trend in 2013)
2013년 html5 총정리 (Summary of HTML5 Trend in 2013)2013년 html5 총정리 (Summary of HTML5 Trend in 2013)
2013년 html5 총정리 (Summary of HTML5 Trend in 2013)Wonsuk Lee
 
Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)
Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)
Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)Wonsuk Lee
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정Javajigi Jaesung
 

Viewers also liked (20)

자바8 스트림 API 소개
자바8 스트림 API 소개자바8 스트림 API 소개
자바8 스트림 API 소개
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰
 
씹고 뜯고 맛보고 즐기는 스트림 API
씹고 뜯고 맛보고 즐기는 스트림 API씹고 뜯고 맛보고 즐기는 스트림 API
씹고 뜯고 맛보고 즐기는 스트림 API
 
자바8 람다식 소개
자바8 람다식 소개자바8 람다식 소개
자바8 람다식 소개
 
keras 빨리 훑어보기(intro)
keras 빨리 훑어보기(intro)keras 빨리 훑어보기(intro)
keras 빨리 훑어보기(intro)
 
Java 자료구조 비교 (Java1.6 기준)
Java 자료구조 비교 (Java1.6 기준)Java 자료구조 비교 (Java1.6 기준)
Java 자료구조 비교 (Java1.6 기준)
 
혼자 있고 싶은 순간 코쿵! (Cocoong)
혼자 있고 싶은 순간 코쿵! (Cocoong)혼자 있고 싶은 순간 코쿵! (Cocoong)
혼자 있고 싶은 순간 코쿵! (Cocoong)
 
1. introduction to java8
1. introduction to java81. introduction to java8
1. introduction to java8
 
자라나는 소프트웨어
자라나는 소프트웨어자라나는 소프트웨어
자라나는 소프트웨어
 
[강의소개] 안드로이드 앱 개발 입문 캠프 4기
[강의소개] 안드로이드 앱 개발 입문 캠프 4기[강의소개] 안드로이드 앱 개발 입문 캠프 4기
[강의소개] 안드로이드 앱 개발 입문 캠프 4기
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
5. 이모셔널 디자인
5. 이모셔널 디자인5. 이모셔널 디자인
5. 이모셔널 디자인
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 
Java JPA
Java JPAJava JPA
Java JPA
 
3. stream api
3. stream api3. stream api
3. stream api
 
Git 더하기 GitHub(Git클라이언트 활용) / Getting started with git+github
Git 더하기 GitHub(Git클라이언트 활용) / Getting started with git+githubGit 더하기 GitHub(Git클라이언트 활용) / Getting started with git+github
Git 더하기 GitHub(Git클라이언트 활용) / Getting started with git+github
 
2014 HTML5 총정리
2014 HTML5 총정리2014 HTML5 총정리
2014 HTML5 총정리
 
2013년 html5 총정리 (Summary of HTML5 Trend in 2013)
2013년 html5 총정리 (Summary of HTML5 Trend in 2013)2013년 html5 총정리 (Summary of HTML5 Trend in 2013)
2013년 html5 총정리 (Summary of HTML5 Trend in 2013)
 
Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)
Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)
Industry trend of HTML5 in 2012 (2012년 HTML5 총정리)
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정
 

Similar to 자바 8 스트림 API

Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...
Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...
Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...AFAS Software
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer developmentAndrey Karpov
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smetnkaluva
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."sjabs
 
Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...
Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...
Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...Big Data Spain
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010RonnBlack
 
Building Analytics Applications with Streaming Expressions in Apache Solr - A...
Building Analytics Applications with Streaming Expressions in Apache Solr - A...Building Analytics Applications with Streaming Expressions in Apache Solr - A...
Building Analytics Applications with Streaming Expressions in Apache Solr - A...Lucidworks
 
Streaming Solr - Activate 2018 talk
Streaming Solr - Activate 2018 talkStreaming Solr - Activate 2018 talk
Streaming Solr - Activate 2018 talkAmrit Sarkar
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseSages
 
Small pieces loosely joined
Small pieces loosely joinedSmall pieces loosely joined
Small pieces loosely joinedennui2342
 

Similar to 자바 8 스트림 API (20)

Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...
Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...
Michiel Overeem (AFAS) - Enterprise software schaalbaar maken met Service Fab...
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Time for Functions
Time for FunctionsTime for Functions
Time for Functions
 
Solving the n + 1 query problem
Solving the n + 1 query problemSolving the n + 1 query problem
Solving the n + 1 query problem
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
Soap tips
Soap tipsSoap tips
Soap tips
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smet
 
Hot Streaming Java
Hot Streaming JavaHot Streaming Java
Hot Streaming Java
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 
Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...
Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...
Apache flink: data streaming as a basis for all analytics by Kostas Tzoumas a...
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
Building Analytics Applications with Streaming Expressions in Apache Solr - A...
Building Analytics Applications with Streaming Expressions in Apache Solr - A...Building Analytics Applications with Streaming Expressions in Apache Solr - A...
Building Analytics Applications with Streaming Expressions in Apache Solr - A...
 
Streaming Solr - Activate 2018 talk
Streaming Solr - Activate 2018 talkStreaming Solr - Activate 2018 talk
Streaming Solr - Activate 2018 talk
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Small pieces loosely joined
Small pieces loosely joinedSmall pieces loosely joined
Small pieces loosely joined
 
CAVE Overview
CAVE OverviewCAVE Overview
CAVE Overview
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

자바 8 스트림 API

  • 1. Java 8 Stream API A differentway to process collections 09:18:24
  • 3. 나즈혼 람다 기본메서드 STREAM API 날짜API 동시성개선 Base 64 메타프로그래밍향상 자바스크립트엔진 2014.3현재버전8.25 09:18:25
  • 4. ListtransactionIds =newArrayList(); for(Transactiont :groceryTransactions) { transactionIds.add(t.getId()); } Collections.sort(groceryTransactions, newComparator() { publicintcompare(Transactiont1, Transactiont2) { returnt2.getValue().compareTo(t1.getValue()); } }); ListgroceryTransactions =newArrayList(); for(Transactiont :groceryTransactions) { if(t.getType() ==Transaction.GROCERY) { groceryTransactions.add(t); } } Java 코드로구매내역구하기 식료품점에서구매한걸찾고 사용금액순으로정렬한뒤 거래내역의ID를추출 09:18:25
  • 5. 그럼Database에서는? SELECT id FROM TRANSACTIONS WHERE type = ‘GROCERY’ ORDER BYvalue DESC 별도의작업없이이미등록된집계함수를사용 SUM, MAX, COUNT, AVG등등 09:18:25
  • 6. ListgroceryTransactions =newArrayList(); for(Transactiont :groceryTransactions) { if(t.getType() ==Transaction.GROCERY) { groceryTransactions.add(t); } } Collections.sort(groceryTransactions, newComparator() { publicintcompare(Transactiont1, Transactiont2) { returnt2.getValue().compareTo(t1.getValue()); } }); ListtransactionIds =newArrayList(); for(Transactiont :groceryTransactions) { transactionIds.add(t.getId()); } 다시한번자바코드 길다! 복잡하다! 코딩해야된다! 09:18:25
  • 7. 그래서준비했습니다! ListtransactionsIds =transactions.stream() .filter(t ->t.getType() ==Transaction.GROCERY) .sorted(Comparator.comparing(Transaction::getValue).reversed()) .map(Transaction::getId) .collect(Collectors.toList()); 람다표현식 메소드참조 09:18:25
  • 8. 일반적인스트림의흐름 filter sorted map collect transactions 2.중간작업(Intermediate Operations) PipeLine 1. 데이터소스 3. 종료작업(Terminal Operations) 09:18:25
  • 9. 중간작업및종료작업 중간작업(Intermediate Operations) •항상스트림을리턴 •Pipeline 형태로연결시킬수잇음 •데이터를처리하기위한로직 •직접처리를시작할수는없음 •오브젝트를리턴하거나, collection 또는void 리턴가능 •Pipeline으로구성된작업을시작 •한번수행되고난후에작업한스트림에재작업불가능 종료작업(Terminal Operations) flatMap map distinct sorted limit peek filter foreach skip toArray reduce collect minmax count anyMatch allMatchnoneMatch firstFind anyFind 09:18:25
  • 10. 좀더상세히 Id : 1 Value : 100 Id : 3 Value : 80 Id : 6 Value : 120 Id : 10 Value : 50 Id : 7 Value : 40 Stream <Transaction) Id : 3 Value : 80 Id : 6 Value : 120 Id : 10 Value : 50 .filter(t ->t.getType() ==Transaction.GROCERY) Stream <Transaction) Id : 6 Value : 120 Id : 3 Value : 80 Id : 10 Value : 50 .sorted( Comparator.comparing( Transaction::getValue).reversed()) Stream <Transaction) 6 3 10 .map(Transaction::getId) Stream <Integer) 6 3 10 .collect(Collectors.toList()); List<Integer) 09:18:25
  • 11. Stream API •Java.util.stream •연산의선언적서술 •반복구조캡슐화, 알고리듬분리 •제어흐름추상화 •함수형방식처리: 데이터불변 •지연처리, 대부분의작업을단일반복수행으로처리 •무한연속데이터흐름API •다양한데이터원천지원: 컬렉션, 생성메서드, 파일I/O 등 09:18:25
  • 12. 컬렉션과스트림 스트림 컬렉션 List Map Set 보관형자료구조 데이터처리추상화 09:18:25
  • 13. 스트림과컬렉션처리방법의차이 •파이프라이닝(Pipelining) •많은스트림의기능들이스트림자기자신을리턴 •처리작업이체인처럼연결되어큰파이프라인처럼동작하도록함 •내부반복(Internal Iteration) •명시적으로반복작업을수행해야되는컬렉션과달리스트림작업은내부에서처리 09:18:25
  • 14. 잠시중간정리 1.질의를할데이터소스(Collection 같은)가필요 2.파이프라인을형성하는중간작업(Intermediate Operations) 3.파이프라인을실행하고결과를리턴하는종료작업(Terminal Operations) Stream 을사용하는일반적인3가지내용 09:18:25
  • 15. java.util.stream •Building Streams •Infinite Streams •Numeric Streams •Filtering •Mapping •Finding and matching •Reducing •Collect 09:18:25
  • 16. Building Streams Stream<Integer>numbersFromValues =Stream.of(1, 2, 3, 4); int[] numbers ={1, 2, 3, 4}; IntStreamnumbersFromArray =Arrays.stream(numbers); longnumberOfLines =Files.lines( Paths.get(“yourFile.txt”), Charset.defaultCharset()) .count(); Collection, 숫자들, 값목록, 배열, 파일 값목록, 배열에서Stream 생성 파일에서Stream 생성 09:18:25
  • 17. Infinite Streams Stream<Integer>numbers =Stream.iterate(0, n ->n +10); numbers.limit(5).forEach(System.out::println); // 0, 10, 20, 30, 40 Stream.iterate Stream.generate 09:18:25
  • 18. Numeric Streams intstatement =transactions.stream() .map(Transaction::getValue) .sum(); // error since Stream has no sum method intstatementSum =transactions.stream() .mapToInt(Transaction::getValue) .sum(); // works! IntStream DoubleStream LongStream mapToInt mapToDouble mapToLong sum(), min(), max(), average(), count() intstatementSum =transactions.stream() .mapToInt(Transaction::getValue) .IntSummaryStatistics(); // IntSummaryStatistics{count=7, sum=28, min=1, average=4.000000, max=7} 09:18:25
  • 19. Filtering •filter •주어진predicate와일치하는stream을리턴 •distinct •중복을제거한유니크엘리먼트stream을리턴 •limit(n) •주어진사이즈(n) 까지의stream을리턴 •skip(n) •주어진엘리먼트길이까지제외한stream을리턴 09:18:25
  • 20. Mapping List<String>words =Arrays.asList("Oracle", "Java", "Magazine"); List<Integer>wordLengths =words.stream() .map(String::length) .collect(toList()); map(String::length) 인자로전달받은값들을가지고새로운Stream 생성 List에저장된단어들의길이를가지고있는새로운list 생성 map(e -> e * 2) map(s -> s.toUpperCase()) 09:18:25
  • 21. Finding and Matching transactions.stream() .filter(t ->t.getType() ==Transaction.GROCERY) .findAny() .ifPresent(System.out::println); booleanexpensive =transactions.stream() .allMatch(t->t.getValue() >100); anyMatch, allMatch, noneMatch Optional<Transaction>=transactions.stream() .filter(t ->t.getType() ==Transaction.GROCERY) .findAny(); findFirst, findAny java.util.Optional 09:18:25
  • 22. Reducing intsum =0; for(intx :numbers) { sum +=x; } intsum =numbers.stream().reduce(0, (a, b) ->a +b); intproduct =numbers.stream().reduce(1, (a, b) ->a *b); intproduct =numbers.stream().reduce(1, Integer::max); for loop 를활용한덧셈 초기화값: 0 BinaryOperator<T> : 두개의엘리멘트를더해새로운값을생성 모든값을곱하기 최대값구하기 엘리먼트들을하나의결과로추출 09:18:25
  • 23. Collect 09:18:25 List<Person>filtered =persons .stream() .filter(p ->p.name.startsWith("P")) .collect(Collectors.toList());// Collectors.toSet() System.out.println(filtered); // [Peter, Pamela] Map<Integer, List<Person>>personsByAge =persons .stream() .collect(Collectors.groupingBy(p ->p.age)); personsByAge .forEach((age, p) ->System.out.format("age %s: %sn", age, p)); // age 18: [Max]// age 23: [Peter, Pamela]// age 12: [David]
  • 24. 정리 1.Stream API 의다양한기능을활용해데이터처리를최적화할수있다. 2.람다와메서드참조를알아두면더좋음! 3.병렬처리를손쉽게지원 •stream() -> parallelStream() 09:18:25
  • 25. 참고자료 1.Processing Data with Java SE 8 Streams •http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html 2.Beyond Java : 자바8을중심으로본자바의혁신 •http://www.slideshare.net/gyumee/beyond-java-8 3.java.util.stream •https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Editor's Notes

  1. Java 8에 추가된 기능인 Steam API에 대해서 알아 보도록 하죠. 혹시 자바 8 사용하고 있는 조직 있나요? 있으면 그분한테 물어보는게 더 확실하게 알 수 있습니다. ㅎ 저는 글로만 배워서 흑흑..
  2. 2014년 3월에 java 8이 출시 됬습니다. 위 같은 다양한 기능들이 같이 추가 됬는데, 이번 발표에서는 STEAM API에 대해서만 알아 보도록 하죠
  3. 이 코드는 구매내역중에서 식료품점에서 쇼핑을 하고 사용금액 순으로 정렬을 한 뒤 거래 내역의 ID를 추출하는 코드 입니다. 뭐 다들 이렇게 작성하시고, 딱히 다른 특이점 도 없습니다. 그럼 다른 언어에서는 어떻게 하는지 한번 비교 해보죠
  4. 데이터베이스에서는 이처럼 한줄의 쿼리만 작성하면 됩니다. 자바와는 다르게 매우 간단하죠? 정렬이 필요 하면 order by 를 쓰면 되고, 집계 관련 작업이 필요하면 이미 등록되어 있는 집계 함수를 사용하면 됩니다
  5. 다시 한번 자바코드를 매의 눈으로 살펴보조.. 음.. 쿼리와 단순 비교하는게 좀 그렇긴 하지만 일단 코드 길이가 길어고 복잡합니다. 반복문도 2개나 있고, 거기다가 반복문안에서 조건 체크까지… 더욱 심각한건 이모든걸 다 코딩을 해줘야 됩니다.
  6. 그래서 준비 했습니다!! 물론 제가 준비한건 아니고.. 이전의 자바 코드를 자바 8의 스트림을 사용하면 이렇게 작성할 수 있습니다. 한눈에 좀 들어 오시나요? 익숙하지 않은 코드가 숨어 있는데… 바로 람다 표현식과 메소드 참조 입니다. 람다 표현식이 자바 8의 꽃이라고 할 수 있는데… 지금은 이런게 있다라고 하고 넘어 가도록 하죠. 정리해서 기술공유에 올리긴 할텐데 그게 언제가 될지…
  7. 이전 코드를 기준으로 일반적인 스트림이 어떻게 진행되는지 알아 보도록 하죠 일단 스트림을 실행시키기 위해서는 데이터 소스가 필요 합니다. 위에서는 거래 내역의 목록이라는 컬렉션을 데이터 소스로 사용했죠 그런 다음에는 중간 작업으로 불리는 메서드들을 연결합니다. 이 중간 작업들은 stream을 반환하기 때문에 서로 연결되서 체인처럼 사용할 수 있는데, jquery 사용해보신 분들은 익숙하실 꺼에요. jquery에서는 메서드 체인으로 부르는데 자바에서는 이런 방식을 fluent interface라고 하는데.. 뭐 직역해보면 유창한? 능수능란한? 자연스럽게 연결해서 사용할 수 있는 거라고 생각하시면됩니다. 이렇게 연결된 중간작업들을 파이프 라인이라고 하고 이는 종료 작업을 통해서 수행됩니다. 스트림을 사용해서 코드를 작성할때 중간작업까지만 만들고 컴파일후실행하면 해당 스트림은 실행되지 않고, 종료 작업이 호출될때만 수행됩니다. 이른 늦은 실행이라고 하는데 laziness loading 과 같은 개념이라고 보면 됩니다.
  8. 거래 내역 목록이 이처럼 구성 되어 있다고 합시다. 처음으로 하는 작업은 식료품점에서 구매한 내역인지 먼저 필터링을 하고 그 다음 가격순으로 정렬을 하고 id를 추출해서 새로운 list로 생성합니다.
  9. 그럼 컬렉션과 스트림은 어떻게 다르냐 컬레션들을 자료들을 보관하기 위한 자료 구조라고 보면 되고 스트림은 이를 처리하기 위한 처리 추상화 자료 구조라고 보면 됩니다. 다른 예를 들어보면 비디오 랜탈샵에 있는 비디오들을 구성하고 있는 프레임이나 바이트들을 컬렉션 데이터로 보면 되고 이를 재생하는 것을 스트림으로 보면됩니다. 네이버뮤직, 멜론같은 음악 스트리밍, 유튜브같은 동영상 스트리밍도 같은 의미라고 보면 됩니다.
  10. 종료 작업인 collec를 사용하면 list, set, map으로 결과를 반환할 수 있고 이 외에도 집계 함수를 사용할 수 있다. .groupingBy, averagingInt, sumarizingInt