SlideShare une entreprise Scribd logo
1  sur  3
Télécharger pour lire hors ligne
1 #####################################################################################
2 #Stream
3 #####################################################################################
4
5 Explain when we use Streams API ?
6
7 Stream is a sequence of objects or primitive types.
8 Operations can be performed on the elements sequentially or in parallel.
9
10 Streams collectors support parallelism even over collections that arent thread-
safe.
11 The way they do this is to have each thread operate independently on its own
collection of intermediate results.
12
13 When a stream is executed in parallel, the map operation processes elements of
the stream.
14 Consequently, the ORDER in which the lambda expression e -> { parallelStorage.add
(e); return e; }
15 adds elements to the List parallelStorage can vary every time the code is run.
16
17 Warnings:
18 Make sure lambda expression parameters in stream operations are not stateful!
19 Do not modify that same list while you are iterating.
20
21 What are Streams lifecycles ?
22
23 creation from:
24 Collection,Array,IO Channel
25 intermediate operations : (The intermediate operations are not evaluated till a
terminal operation is called)
26 filter,flatMap,distinct,peek,map
27 terminal operation:
28 forEach,count,collect,allMatch,anyMatch
29
30 How to sum values from 1 - 100 ?
31
32 IntStream.range(1, 100)
33 .reduce(0, Integer::sum);
34 //or use
35 IntStream.range(1, 100)
36 .sum();
37
38 How to get maximum value from Integer array ?
39
40 Integer[] a = {1, 3, 4, 6, 33, 1};
41
42 System.out.println(Arrays.stream(a)
43 .max(Integer::compareTo)
44 );
45 //OR
46 System.out.println(Arrays.stream(a)
47 .reduce(0,Integer::max)
48 );
49
50 How to get stream of objects ?
51
52 Stream.of(...);
53
54 How to copy strings from old list into a new list
55
56 List<String> oldItemList = new ArrayList<>();
57 List<String> newitemList = olditemList.stream().collect(Collectors.toList());
58
59 How to make a stream processing parallel ?
60
61 roster
62 .stream()
63 .parallelStream() //use with caution as it uses fork join pool, by default
it has one less threads as you have processors,
64 .filter(e -> e.getGender() == Person.Sex.MALE) // An intermediate
operation, such as filter, produces a new stream.
65 .forEach(e -> System.out.println(e.getName())); // terminal operation, such
as forEach, produces a non-stream result
66
67 How to run the parallelStream() in a different thread pool ?
68
69 ForkJoinPool forkJoinPool = new ForkJoinPool(2);
70 CompletableFuture<List<Integer>> primes = CompletableFuture.supplyAsync(() ->
71 IntStream.range(1, 1_000_000)
72 .parallel()
73 .collect(toList()),
74 forkJoinPool
75 );
76
77 How to produce 1-10 stream ?
78
79 IntStream.range(1,10).stream()
80
81 How to check the result of Stream is not null ?
82
83 values.stream()
84 .filter(s -> s.equals("two"))
85 .findAny()
86 .ifPresent(s -> {throw new RuntimeException("not found");});
87
88 How to assign action when result of stream is null ?
89
90 String s = strings.stream()
91 .filter(e -> e.equals("3"))
92 .findAny()
93 .orElse(new String("3"));
94
95 How to find if the element is on the list ?
96
97 List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz",
"reggae","pop"));
98 genre.stream().allMatch(s -> !s.isEmpty()); //all must match
99 genre.stream().anyMatch(s -> s.indexOf("r") == 0); //at least 1 must match
100 System.out.println(genre.stream().distinct().count()); // prints 4
101 genre.stream().map(String::toUpperCase).forEach(System.out::println); //prints
each element in Uppercase
102
103 How to print out a map collection?
104
105 Map<String, List<String>> artists = new HashMap<String, List<String>>();
106 artists.put("rock", new ArrayList<String>(Arrays.asList("rockArtistA",
"rockArtistB")));
107 artists.put("pop", new ArrayList<String>(Arrays.asList("popArtistA", "popArtistB"
)));
108 genre.stream().flatMap(s -> artists.get(s).stream()).forEach(s -> System.out.
print(" " + s));
109 // prints rockArtistA rockArtistB popArtistA popArtistB
110
111 How to group map collection by map key?
112
113 public Map<Region.Wojewodztwo, List<Region>> groupSubregionByWojewodztwo() {
114 List<Region> list = Region.RegionRepository.bezrobocie2014();
115 return list.stream().collect(Collectors.groupingBy(e -> e.getWojewodztwo()));
116 }
117
118 How to group map collection by map key?
119
120 public String print£ódzkieRegions() {
121 List<Region> list = Region.RegionRepository.bezrobocie2014();
122 return
123 list.stream()
124 .filter(e -> e.getWojewodztwo().equals(Region.Wojewodztwo.
£ÓDZKIE))
125 .map(e -> e.getNazwa())
126 .peek(System.out::println)
127 .collect(Collectors.joining(" i ", "Podregiony ³ódzkie to: ",
"."));
128 //connects all values into 1 string with PREFIX and SUFIX
129 }
130
131 How to compare all values in stream using custom comparison function?
132
133 public Region getRegionWithLowestStopaBezrobocia() {
134 List<Region> list = Region.RegionRepository.bezrobocie2014();
135 return list
136 .stream()
137 .reduce((a, b) -> a.getStopaBezrobocia() > b.getStopaBezrobocia()?b:a)
138 .get();
139 }
140
141 How to split a string using regex pattern
142
143 Pattern.compile(":")
144 .splitAsStream("foobar:foo:bar")
145 .filter(s -> s.contains("bar"))
146 .sorted()
147 .collect(Collectors.joining(":"));
148 // => bar:foobar
149
150 // or alternatively
151 Pattern pattern = Pattern.compile(".*@gmail.com");
152 Stream.of("bob@gmail.com", "alice@hotmail.com")
153 .filter(pattern.asPredicate())
154 .count();
155 // => 1
156
157 How to list files in current directory
158
159 try (Stream<Path> stream = Files.list(Paths.get(""))) {
160 String joined = stream
161 .map(String::valueOf)
162 .filter(path -> !path.startsWith("."))
163 .sorted()
164 .collect(Collectors.joining("; "));
165 System.out.println("List: " + joined);
166 } //must use try with resource to explicitly close directory stream
167
168 How to print a file
169
170 try (Stream<String> stream = Files.lines(Paths.get("res/nashorn1.js"))) {
171 stream
172 .filter(line -> line.contains("print"))
173 .map(String::trim)
174 .forEach(System.out::println);
175 }
176
177 //OR
178 Path path = Paths.get("res/nashorn1.js");
179 try (BufferedReader reader = Files.newBufferedReader(path)) {
180 long countPrints = reader
181 .lines()
182 .filter(line -> line.contains("print"))
183 .count();
184 System.out.println(countPrints);
185 }
186
187 How to sum all properties ?
188
189 ships.stream().mapToInt(ss -> ss.getSunk()).sum()
190
191 How to Count on objects with group by id?
192
193 list.stream()
194 .collect(Collectors.groupingBy(foo -> foo.id, Collectors.counting()))
195 .forEach((id,count)->System.out.println(id+"t"+count));
196
197 How to Sum on objects property with group by id?
198
199 list.stream()
200 .collect(Collectors.groupingBy(foo -> foo.id,
201 Collectors.summingInt(foo->foo.targetCost)))
202 .forEach((id,sumTargetCost)->System.out.println(id+"t"+sumTargetCost));
203

Contenu connexe

Tendances

JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum
patricklee
 

Tendances (20)

Efficient Use of indexes in MySQL
Efficient Use of indexes in MySQLEfficient Use of indexes in MySQL
Efficient Use of indexes in MySQL
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
 
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
 
fabfile.py
fabfile.pyfabfile.py
fabfile.py
 
Connecting Pebble to the World
Connecting Pebble to the WorldConnecting Pebble to the World
Connecting Pebble to the World
 
dotCloud and go
dotCloud and godotCloud and go
dotCloud and go
 
Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
 
gunicorn introduction
gunicorn introductiongunicorn introduction
gunicorn introduction
 
Finding a lost song with Node.js and async iterators
Finding a lost song with Node.js and async iteratorsFinding a lost song with Node.js and async iterators
Finding a lost song with Node.js and async iterators
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Play á la Rails
Play á la RailsPlay á la Rails
Play á la Rails
 
DataEngConf SF16 - Routing Billions of Analytics Events with High Deliverability
DataEngConf SF16 - Routing Billions of Analytics Events with High DeliverabilityDataEngConf SF16 - Routing Billions of Analytics Events with High Deliverability
DataEngConf SF16 - Routing Billions of Analytics Events with High Deliverability
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum
 
Cooking pies with Celery
Cooking pies with CeleryCooking pies with Celery
Cooking pies with Celery
 

Similaire à Java Streams Interview short reminder with examples

Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
Michael Barker
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humans
Craig Kerstiens
 

Similaire à Java Streams Interview short reminder with examples (20)

Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at... Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humans
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
 
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
Analytics at Speed: Introduction to ClickHouse and Common Use Cases. By Mikha...
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data Pipelines
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for Developers
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 

Plus de Mark Papis

Plus de Mark Papis (8)

Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Java vs Web security Cheat Sheet
Java vs Web security Cheat SheetJava vs Web security Cheat Sheet
Java vs Web security Cheat Sheet
 
Java technical stack Cheat Sheet
Java technical stack Cheat SheetJava technical stack Cheat Sheet
Java technical stack Cheat Sheet
 
Spring cheat sheet
Spring cheat sheetSpring cheat sheet
Spring cheat sheet
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat Sheet
 
Java inheritance cheat sheet
Java inheritance cheat sheetJava inheritance cheat sheet
Java inheritance cheat sheet
 
Java Collections comparison Cheat Sheet
Java Collections comparison Cheat SheetJava Collections comparison Cheat Sheet
Java Collections comparison Cheat Sheet
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

Java Streams Interview short reminder with examples

  • 1. 1 ##################################################################################### 2 #Stream 3 ##################################################################################### 4 5 Explain when we use Streams API ? 6 7 Stream is a sequence of objects or primitive types. 8 Operations can be performed on the elements sequentially or in parallel. 9 10 Streams collectors support parallelism even over collections that arent thread- safe. 11 The way they do this is to have each thread operate independently on its own collection of intermediate results. 12 13 When a stream is executed in parallel, the map operation processes elements of the stream. 14 Consequently, the ORDER in which the lambda expression e -> { parallelStorage.add (e); return e; } 15 adds elements to the List parallelStorage can vary every time the code is run. 16 17 Warnings: 18 Make sure lambda expression parameters in stream operations are not stateful! 19 Do not modify that same list while you are iterating. 20 21 What are Streams lifecycles ? 22 23 creation from: 24 Collection,Array,IO Channel 25 intermediate operations : (The intermediate operations are not evaluated till a terminal operation is called) 26 filter,flatMap,distinct,peek,map 27 terminal operation: 28 forEach,count,collect,allMatch,anyMatch 29 30 How to sum values from 1 - 100 ? 31 32 IntStream.range(1, 100) 33 .reduce(0, Integer::sum); 34 //or use 35 IntStream.range(1, 100) 36 .sum(); 37 38 How to get maximum value from Integer array ? 39 40 Integer[] a = {1, 3, 4, 6, 33, 1}; 41 42 System.out.println(Arrays.stream(a) 43 .max(Integer::compareTo) 44 ); 45 //OR 46 System.out.println(Arrays.stream(a) 47 .reduce(0,Integer::max) 48 ); 49 50 How to get stream of objects ? 51 52 Stream.of(...); 53 54 How to copy strings from old list into a new list 55 56 List<String> oldItemList = new ArrayList<>(); 57 List<String> newitemList = olditemList.stream().collect(Collectors.toList()); 58 59 How to make a stream processing parallel ? 60 61 roster 62 .stream() 63 .parallelStream() //use with caution as it uses fork join pool, by default it has one less threads as you have processors, 64 .filter(e -> e.getGender() == Person.Sex.MALE) // An intermediate operation, such as filter, produces a new stream. 65 .forEach(e -> System.out.println(e.getName())); // terminal operation, such as forEach, produces a non-stream result
  • 2. 66 67 How to run the parallelStream() in a different thread pool ? 68 69 ForkJoinPool forkJoinPool = new ForkJoinPool(2); 70 CompletableFuture<List<Integer>> primes = CompletableFuture.supplyAsync(() -> 71 IntStream.range(1, 1_000_000) 72 .parallel() 73 .collect(toList()), 74 forkJoinPool 75 ); 76 77 How to produce 1-10 stream ? 78 79 IntStream.range(1,10).stream() 80 81 How to check the result of Stream is not null ? 82 83 values.stream() 84 .filter(s -> s.equals("two")) 85 .findAny() 86 .ifPresent(s -> {throw new RuntimeException("not found");}); 87 88 How to assign action when result of stream is null ? 89 90 String s = strings.stream() 91 .filter(e -> e.equals("3")) 92 .findAny() 93 .orElse(new String("3")); 94 95 How to find if the element is on the list ? 96 97 List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz", "reggae","pop")); 98 genre.stream().allMatch(s -> !s.isEmpty()); //all must match 99 genre.stream().anyMatch(s -> s.indexOf("r") == 0); //at least 1 must match 100 System.out.println(genre.stream().distinct().count()); // prints 4 101 genre.stream().map(String::toUpperCase).forEach(System.out::println); //prints each element in Uppercase 102 103 How to print out a map collection? 104 105 Map<String, List<String>> artists = new HashMap<String, List<String>>(); 106 artists.put("rock", new ArrayList<String>(Arrays.asList("rockArtistA", "rockArtistB"))); 107 artists.put("pop", new ArrayList<String>(Arrays.asList("popArtistA", "popArtistB" ))); 108 genre.stream().flatMap(s -> artists.get(s).stream()).forEach(s -> System.out. print(" " + s)); 109 // prints rockArtistA rockArtistB popArtistA popArtistB 110 111 How to group map collection by map key? 112 113 public Map<Region.Wojewodztwo, List<Region>> groupSubregionByWojewodztwo() { 114 List<Region> list = Region.RegionRepository.bezrobocie2014(); 115 return list.stream().collect(Collectors.groupingBy(e -> e.getWojewodztwo())); 116 } 117 118 How to group map collection by map key? 119 120 public String print£ódzkieRegions() { 121 List<Region> list = Region.RegionRepository.bezrobocie2014(); 122 return 123 list.stream() 124 .filter(e -> e.getWojewodztwo().equals(Region.Wojewodztwo. £ÓDZKIE)) 125 .map(e -> e.getNazwa()) 126 .peek(System.out::println) 127 .collect(Collectors.joining(" i ", "Podregiony ³ódzkie to: ", ".")); 128 //connects all values into 1 string with PREFIX and SUFIX 129 } 130 131 How to compare all values in stream using custom comparison function?
  • 3. 132 133 public Region getRegionWithLowestStopaBezrobocia() { 134 List<Region> list = Region.RegionRepository.bezrobocie2014(); 135 return list 136 .stream() 137 .reduce((a, b) -> a.getStopaBezrobocia() > b.getStopaBezrobocia()?b:a) 138 .get(); 139 } 140 141 How to split a string using regex pattern 142 143 Pattern.compile(":") 144 .splitAsStream("foobar:foo:bar") 145 .filter(s -> s.contains("bar")) 146 .sorted() 147 .collect(Collectors.joining(":")); 148 // => bar:foobar 149 150 // or alternatively 151 Pattern pattern = Pattern.compile(".*@gmail.com"); 152 Stream.of("bob@gmail.com", "alice@hotmail.com") 153 .filter(pattern.asPredicate()) 154 .count(); 155 // => 1 156 157 How to list files in current directory 158 159 try (Stream<Path> stream = Files.list(Paths.get(""))) { 160 String joined = stream 161 .map(String::valueOf) 162 .filter(path -> !path.startsWith(".")) 163 .sorted() 164 .collect(Collectors.joining("; ")); 165 System.out.println("List: " + joined); 166 } //must use try with resource to explicitly close directory stream 167 168 How to print a file 169 170 try (Stream<String> stream = Files.lines(Paths.get("res/nashorn1.js"))) { 171 stream 172 .filter(line -> line.contains("print")) 173 .map(String::trim) 174 .forEach(System.out::println); 175 } 176 177 //OR 178 Path path = Paths.get("res/nashorn1.js"); 179 try (BufferedReader reader = Files.newBufferedReader(path)) { 180 long countPrints = reader 181 .lines() 182 .filter(line -> line.contains("print")) 183 .count(); 184 System.out.println(countPrints); 185 } 186 187 How to sum all properties ? 188 189 ships.stream().mapToInt(ss -> ss.getSunk()).sum() 190 191 How to Count on objects with group by id? 192 193 list.stream() 194 .collect(Collectors.groupingBy(foo -> foo.id, Collectors.counting())) 195 .forEach((id,count)->System.out.println(id+"t"+count)); 196 197 How to Sum on objects property with group by id? 198 199 list.stream() 200 .collect(Collectors.groupingBy(foo -> foo.id, 201 Collectors.summingInt(foo->foo.targetCost))) 202 .forEach((id,sumTargetCost)->System.out.println(id+"t"+sumTargetCost)); 203