Enviar búsqueda
Cargar
Java8 stream
•
11 recomendaciones
•
2,267 vistas
koji lin
Seguir
Tecnología
Denunciar
Compartir
Denunciar
Compartir
1 de 55
Descargar ahora
Descargar para leer sin conexión
Recomendados
Refactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
jq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
Istanbul Tech Talks
Poor Man's Functional Programming
Poor Man's Functional Programming
Dmitry Buzdin
Introduction to JQ
Introduction to JQ
Knoldus Inc.
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
John De Goes
The Ring programming language version 1.8 book - Part 39 of 202
The Ring programming language version 1.8 book - Part 39 of 202
Mahmoud Samir Fayed
Más contenido relacionado
La actualidad más candente
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
Platonov Sergey
Algorithm and Programming (Array)
Algorithm and Programming (Array)
Adam Mukharil Bachtiar
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
Beyond tf idf why, what & how
Beyond tf idf why, what & how
lucenerevolution
Halogen: Past, Present, and Future
Halogen: Past, Present, and Future
John De Goes
Virtual machine and javascript engine
Virtual machine and javascript engine
Duoyi Wu
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
Luka Jacobowitz
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
John De Goes
friends functionToshu
friends functionToshu
Sidd Singh
Lambda выражения и Java 8
Lambda выражения и Java 8
Alex Tumanoff
Profiling and optimization
Profiling and optimization
g3_nittala
MTL Versus Free
MTL Versus Free
John De Goes
Python Performance 101
Python Performance 101
Ankur Gupta
Scala @ TomTom
Scala @ TomTom
Eric Bowman
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
Platonov Sergey
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
Badoo Development
Scala introduction
Scala introduction
vito jeng
Knolx session
Knolx session
Knoldus Inc.
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
John De Goes
Introduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
La actualidad más candente
(20)
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
Algorithm and Programming (Array)
Algorithm and Programming (Array)
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Beyond tf idf why, what & how
Beyond tf idf why, what & how
Halogen: Past, Present, and Future
Halogen: Past, Present, and Future
Virtual machine and javascript engine
Virtual machine and javascript engine
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
friends functionToshu
friends functionToshu
Lambda выражения и Java 8
Lambda выражения и Java 8
Profiling and optimization
Profiling and optimization
MTL Versus Free
MTL Versus Free
Python Performance 101
Python Performance 101
Scala @ TomTom
Scala @ TomTom
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
Scala introduction
Scala introduction
Knolx session
Knolx session
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
Introduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
Destacado
Designing Intelligent Content: A Writer's Guide
Designing Intelligent Content: A Writer's Guide
Niki Blaker
Java8 lambda
Java8 lambda
koji lin
PHX Startup Week - Designing Intelligent Content for Entrepreneurs
PHX Startup Week - Designing Intelligent Content for Entrepreneurs
Niki Blaker
QML 與 C++ 的美麗邂逅
QML 與 C++ 的美麗邂逅
Jack Yang
超酷炫科幻 UI:QML 入門
超酷炫科幻 UI:QML 入門
Fred Chien
Presenters Tool Belt - What Every Presenter Should Carry
Presenters Tool Belt - What Every Presenter Should Carry
Empowered Presentations
Connect With Your Audience
Connect With Your Audience
Slides That Rock
Cleaning Your Cool Brand
Cleaning Your Cool Brand
Slides That Rock
Social Media Engagement is Not a Strategy
Social Media Engagement is Not a Strategy
Mark Schaefer
13 Inspiring Quotes about Design
13 Inspiring Quotes about Design
Ethos3
3 Storytelling Tips - From Acclaimed Writer Burt Helm
3 Storytelling Tips - From Acclaimed Writer Burt Helm
Ethos3
Your Speech is Toxic
Your Speech is Toxic
Chiara Ojeda
8 Free Types of Marketing Strategies
8 Free Types of Marketing Strategies
Brian Downard
Destacado
(13)
Designing Intelligent Content: A Writer's Guide
Designing Intelligent Content: A Writer's Guide
Java8 lambda
Java8 lambda
PHX Startup Week - Designing Intelligent Content for Entrepreneurs
PHX Startup Week - Designing Intelligent Content for Entrepreneurs
QML 與 C++ 的美麗邂逅
QML 與 C++ 的美麗邂逅
超酷炫科幻 UI:QML 入門
超酷炫科幻 UI:QML 入門
Presenters Tool Belt - What Every Presenter Should Carry
Presenters Tool Belt - What Every Presenter Should Carry
Connect With Your Audience
Connect With Your Audience
Cleaning Your Cool Brand
Cleaning Your Cool Brand
Social Media Engagement is Not a Strategy
Social Media Engagement is Not a Strategy
13 Inspiring Quotes about Design
13 Inspiring Quotes about Design
3 Storytelling Tips - From Acclaimed Writer Burt Helm
3 Storytelling Tips - From Acclaimed Writer Burt Helm
Your Speech is Toxic
Your Speech is Toxic
8 Free Types of Marketing Strategies
8 Free Types of Marketing Strategies
Similar a Java8 stream
C++ process new
C++ process new
敬倫 林
Managing console
Managing console
Shiva Saxena
2 BytesC++ course_2014_c3_ function basics¶meters and overloading
2 BytesC++ course_2014_c3_ function basics¶meters and overloading
kinan keshkeh
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Sages
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
Christian Nagel
Java8lambda
Java8lambda
Isuru Samaraweera
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
Andrey Karpov
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
C++ file
C++ file
Mukund Trivedi
C++ file
C++ file
Mukund Trivedi
Python高级编程(二)
Python高级编程(二)
Qiangning Hong
Lecture 9_Classes.pptx
Lecture 9_Classes.pptx
NelyJay
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
Jan Wedekind
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov
Lecture05
Lecture05
elearning_portal
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
Isuru Samaraweera
Library functions in c++
Library functions in c++
Neeru Mittal
C++ Write a recursive function that receives an integer array along wi.docx
C++ Write a recursive function that receives an integer array along wi.docx
marions12
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
nsm.nikhil
The STL
The STL
adil raja
Similar a Java8 stream
(20)
C++ process new
C++ process new
Managing console
Managing console
2 BytesC++ course_2014_c3_ function basics¶meters and overloading
2 BytesC++ course_2014_c3_ function basics¶meters and overloading
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
Java8lambda
Java8lambda
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
C++ file
C++ file
C++ file
C++ file
Python高级编程(二)
Python高级编程(二)
Lecture 9_Classes.pptx
Lecture 9_Classes.pptx
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Lecture05
Lecture05
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
Library functions in c++
Library functions in c++
C++ Write a recursive function that receives an integer array along wi.docx
C++ Write a recursive function that receives an integer array along wi.docx
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
The STL
The STL
Más de koji lin
サーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよ
koji lin
G1GC
G1GC
koji lin
Using armeria to write your RPC
Using armeria to write your RPC
koji lin
使用 Java 上的 future/promise API
使用 Java 上的 future/promise API
koji lin
Annotation processing and code gen
Annotation processing and code gen
koji lin
Jcconf
Jcconf
koji lin
Use Lambdas in Android
Use Lambdas in Android
koji lin
docker intro
docker intro
koji lin
Java8 time
Java8 time
koji lin
Idea13
Idea13
koji lin
CompletableFuture
CompletableFuture
koji lin
Raspberry Pi with Java
Raspberry Pi with Java
koji lin
Services you can use to monitor and analyze mobile app
Services you can use to monitor and analyze mobile app
koji lin
Programming with Threads in Java
Programming with Threads in Java
koji lin
JQuery
JQuery
koji lin
山頂洞人日記 - 回歸到最純樸的開發
山頂洞人日記 - 回歸到最純樸的開發
koji lin
Android Location-based應用開發分享
Android Location-based應用開發分享
koji lin
Más de koji lin
(17)
サーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよ
G1GC
G1GC
Using armeria to write your RPC
Using armeria to write your RPC
使用 Java 上的 future/promise API
使用 Java 上的 future/promise API
Annotation processing and code gen
Annotation processing and code gen
Jcconf
Jcconf
Use Lambdas in Android
Use Lambdas in Android
docker intro
docker intro
Java8 time
Java8 time
Idea13
Idea13
CompletableFuture
CompletableFuture
Raspberry Pi with Java
Raspberry Pi with Java
Services you can use to monitor and analyze mobile app
Services you can use to monitor and analyze mobile app
Programming with Threads in Java
Programming with Threads in Java
JQuery
JQuery
山頂洞人日記 - 回歸到最純樸的開發
山頂洞人日記 - 回歸到最純樸的開發
Android Location-based應用開發分享
Android Location-based應用開發分享
Último
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
xtailishbaloch
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? Webinar
ThousandEyes
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
DianaGray10
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
Francesco Corti
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
IPLOOK Networks
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
Knoldus Inc.
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
Infopole1
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applications
nooralam814309
From the origin to the future of Open Source model and business
From the origin to the future of Open Source model and business
Francesco Corti
3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data
Eric D. Schabell
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility WTS FEST
BillieHyde
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
DianaGray10
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...
DianaGray10
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
shyamraj55
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Neo4j
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024
Brian Pichman
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
Brian Pichman
Top 10 Squarespace Development Companies
Top 10 Squarespace Development Companies
TopCSSGallery
Último
(20)
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? Webinar
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applications
From the origin to the future of Open Source model and business
From the origin to the future of Open Source model and business
3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility WTS FEST
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
Top 10 Squarespace Development Companies
Top 10 Squarespace Development Companies
Java8 stream
1.
Java 8 Stream @kojilin 2014/3/29@TWJUG
2.
Stream •java.util.stream •Support functional-style operations
on streams of elements int sum = widgetList.stream() .filter(b -> b.color == RED) .mapToInt(b -> b.getWeight()) .sum();
3.
External Iteration long sum
= 0; for(int i = 0; i < N; ++i){ sum += i * i; }
4.
Internal Iteration long sum
= LongStream .range(0, N) .map(i -> i * i) .sum();
5.
•為什麼需要 Stream ? •從外部迭代轉為內部迭代 •外部迭代需要注意要做什麼跟如何做 •內部迭代著重在要做什麼比如何做更多 •將行為資料化 •讓函式庫幫你更多的忙 •讓程式碼更簡潔好讀
6.
Stream •Stream 不是資料結構,沒有 存資料 •包裹在現有的資料結構之上 •透過內部迭代 •Multi-thread •Laziness •Stream
有 iterator 方法,但沒有實作 Iterable •所以不能寫 for (String item : stream)
7.
Stream 的種類 •Stream<T> •Primitive Streams •IntStream •DoubleStream •LongStream •彼此之間可以透過像
mapToInt, mapToDouble, mapToObj 等方式切換
8.
Stream 的使用方式 long sum
= LongStream .range(0, N) .map(i -> i * i) .filter(i -> i % 2 == 0) .sum(); •建立 Stream
9.
Stream 的使用方式 long sum
= LongStream .range(0, N) .map(i -> i * i) .filter(i -> i % 2 == 0) .sum(); •透過連續的 intermediate operation 操作
10.
Stream 的使用方式 long sum
= LongStream .range(0, N) .map(i -> i * i) .filter(i -> i % 2 == 0) .sum(); •最後用 terminal operation 結束
11.
如何取得 Stream? •Collection#stream() •Arrays.stream(Object[]) •Stream.of(Object[]) •IntStream.range(int, int) •BufferedReader#lines() •Stream#filter() •etc.
12.
Intermediate Operation •回傳 Stream,可以接下一個
operation •Lazy •直到遇到 terminal operation 的方法前不 會有效果
13.
•filter •map •flatMap •sorted stream.filter( p ->
p > 20); stream.map( p -> p.name); stream.flatMap( p -> p.cars.stream()); stream.sorted(p1, p2 -> p1.name.compareTo(p2.name));
14.
•limit •distinct •skip stream.limit(5); stream.distinct(); stream.skip(5);
15.
Stateful & Stateless •Stateful
表示在操作元素時,除了當下的元 素外需要考慮其他狀態 •sorted, skip, limit •Stateless 表示在操作元素時,除了當下的元 素外不用考慮其他狀態 •filter, map
16.
Terminal Operation •不會回傳 stream,整個
stream 只能有一個 terminal operation 呼叫 •呼叫後才會開始走查 stream,最後產生並回 傳結果或是製造 side-effect •呼叫完 terminal operation 後 stream 會被 當作被使用完畢 •Stream -> (Intermediate)* -> Terminal
17.
•forEach •reduce •collect •count stream.forEach( p ->
print(p)); stream.reduce( 0, (a, b) -> a + b); stream.collect( Collectors.toList()); stream.count();
18.
•toArray •max •sum ( Primitive
Stream ) •average ( Primitive Stream ) stream.toArray(String[]::new); stream.max(String::compareTo); intStream.sum(); intStream.average();
19.
Reduction •將元素組合成一個結果 •reduce, collect, sum,
max, count intStream.sum(); numbers.stream().reduce(0, (x,y) -> x + y);
20.
<U> U reduce( U
identity, BiFunction<U, ? super T, U > accumulator, BinaryOperator<U> combiner); Stream<T>#reduce •accumulator 和 combiner 每次處理完元素 後,必須回傳新的值
21.
Integer result =
stream.reduce(0, (sum, b) -> sum + b.getWeight(), Integer::sum); Stream<T>#reduce
22.
list.stream().reduce( new ArrayList<>(), (integers, o)
-> { integers.add(o); return integers; }, (integers, integers2) -> { integers.addAll(integers2); return integers; }); ❌
23.
list.stream().reduce( new ArrayList<>(), (integers, o)
-> { ArrayList<Integer> list = new ArrayList<>(integers); list.add(o); return list; }, (integers, integers2) -> { ArrayList<Integer> list = new ArrayList<>(integers); list.addAll(integers2); return list; }); △
24.
Mutable Reduction •將元素累加到 mutable
的容器中 •Stream#collect •和 reduce 不同,是改變已經存在的值
25.
<R> R collect( Supplier<R>
supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner); Stream<T>#collect •accumulator 和 combiner 都是 consumer
26.
ArrayList<String> asList = stringStream.collect( ArrayList::new, ArrayList::add, ArrayList::addAll); Stream<T>#collect
27.
<R> R collect( Collector<?
super T,A,R> collector); Stream<T>#collect •Collector 並不是很容易實作
28.
•所以 Collectors 提供了許多預設的方法提供 常用的
Collector •toList, groupingBy, toSet, toMap, counting stream.collect(Collectors.toList()); stream.collect(Collectors .groupingBy(…)); strStream.collect(Collectors .join(","));
29.
???
30.
????
31.
! List<Item> items =
new ArrayList<>…; Map<String, List<Item>> result = items.stream().collect(groupingBy( Item::getOwner)); ! >> {owner1=[i1, i2], owner2=[i3],…}
32.
! List<Item> items =
new ArrayList<>…; Map<String, Set<String>> result = items.stream().collect(groupingBy( Item::getOwner, toSet())); >> {owner1=[i1], owner2=[i3], …}
33.
List<Item> items =
new ArrayList<>…; Map<String, Set<String>> result = items.stream().collect(groupingBy( Item::getOwner, mapping(Item::getName(), toSet()))); ! >> {owner1=[name1], owner2=[name2],…}
34.
Lazy Evaluation List<Integer> items
= Arrays.asList(1, 2, 3, 4); items.stream() .filter( i -> { sout("A"+i); i % 2 == 0; }) .map( i -> { sout("B"+i); return i; }) .map( i -> { sout("C"+i); return i; }); •不會印出東西
35.
Lazy Evaluation List<Integer> items
= Arrays.asList(1, 2, 3, 4); items.stream() .filter( i -> { sout("A"+i); i % 2 == 0; }) .map( i -> { sout("B"+i); return i; }) .map( i -> { sout("C"+i); return i; }) .collect(toList());
36.
Lazy Evaluation List<Integer> items
= Arrays.asList(1, 2, 3, 4); items.stream() .filter( i -> { sout("A"+i); i % 2 == 0; }) .map( i -> { sout("B"+i); return i; }) .map( i -> { sout("C"+i); return i; }) .collect(toList()); >> A1, A2, B2, C2, A3, A4, B4, C4
37.
Parallel List<Integer> items =
Arrays.asList(1, 2, 3, 4); items.parallelStream() .filter( i -> { sout("A"+i); return i % 2 == 0; }) .map( i -> { sout("B"+i); return i; }) .map( i -> { sout("C"+i); return i; }) .collect(toList()); >> A1, A3, A4, A2, B4, B2, C2, C4
38.
Short-circuit Operation •Intermediate operation •能將無限的輸入轉換成有限的
stream •limit long sum = IntStream .iterate(1, n -> n+1) .limit(10) .sum();
39.
Short-circuit Operation •Terminal operation •能將無限的輸入,
在有限時間內結束 •findFirst, anyMatch, allMatch long sum = IntStream .iterate(1, n -> n+1) .filter(i -> i > 100) .findFirst();
40.
Example 1 •找出第一個 age
> 20 的 Student for (Student student : students) { if (student.age > 20) { return student; } } }
41.
Optional<Student> student =
students.stream() .filter(s -> s.age > 20) .findFirst();
42.
Example 2 •尋找 age
> 20,成績 > 90 的 10 位 Student 的 id
43.
List<String> result =
…; for (Student student : students) { if (student.age > 20 && student.grade > 90) { result.add(student.id); if(result.size() >= 10){ break; } } }
44.
List<String> result =
students.stream() .filter(student -> student.age > 20) .filter(student -> student.grade > 90) .limit(10) .map(student -> student.id) .collect(Collectors.toList());
45.
Example 3 •找出所有 Article
評論大於 20 的 Category,並依照名稱排序。
46.
List<Category> result =
…; for (Category category : categories) { for (Article a : c.getArticles()) { if (a.getCommentCount() >= 20) { result.add(c); break; } } } Collections.sort(result, Comparator.comparing(c -> c.getName()));
47.
categories.stream() .filter(c -> c.getArticles() .stream() .anyMatch(a
-> a.getCommentCount() >= 20)) .sorted(Comparator.comparing(c -> c.getName())) .collect(Collectors.toList());
48.
Example 4 •將 Person
依照年齡分類到不同 List •Map<Integer, List< Person >>
49.
Map<Integer, List<Person>> result
= …; for (Person person : people) { result.computeIfAbsent(person.age, t -> new ArrayList<>()) .add(person); }
50.
Map<Integer,List<Person>> peopleByAge = people.stream() .collect(groupingBy(Person::getAge));
51.
•Stream 走查很容易跟預期的不同,所以操作 過程要避免產生副作用 •順序,走了 些元素,是否並行 注意
52.
ArrayList<String> results =
new ArrayList<>(); stream.filter(…) .forEach(s -> results.add(s)); List<String>results = stream .filter(…) .collect(Collectors.toList()); Side Effects
53.
Set<Integer> seen =
Collections.synchronizedSet( new HashSet<>()); stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })... Stateless Behaviors
54.
List<String> source =
...; source.stream() .filter(s -> { source.add(...); return s.length() > 10; }) ... Non-inferences •走查過程中不該動到來源資料結構 •除非該資料結構是支援 concurrent 存取
55.
•使用 Stream 的方式和外部迭代差異不小 •很多方法只看參數型態很難理解,從方法和 變數名稱去理解使用方式 •只能多寫多習慣 •通常寫完後會有較佳的可讀性 最後
Descargar ahora