SlideShare uma empresa Scribd logo
1 de 3
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Efficient Use of indexes in MySQL
Efficient Use of indexes in MySQLEfficient Use of indexes in MySQL
Efficient Use of indexes in MySQLAleksandr Kuzminsky
 
Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous Shmuel Fomberg
 
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"GeeksLab Odessa
 
Connecting Pebble to the World
Connecting Pebble to the WorldConnecting Pebble to the World
Connecting Pebble to the WorldPebble Technology
 
Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話dcubeio
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Workhorse Computing
 
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 DepthC4Media
 
gunicorn introduction
gunicorn introductiongunicorn introduction
gunicorn introductionAdam Lowry
 
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 iteratorsLuciano Mammino
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perldeepfountainconsulting
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
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 DeliverabilityHakka Labs
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)xSawyer
 
JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraumpatricklee
 

Mais procurados (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
 

Semelhante a Java Streams Interview short reminder with examples

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 wayOleg Podsechin
 
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 BarkerJAX London
 
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
 
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...Big Data Spain
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
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 2015Codemotion
 
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...Mario Fusco
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humansCraig Kerstiens
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
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...Altinity Ltd
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data PipelinesHostedbyConfluent
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersDevDay Dresden
 
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 concurrencykshanth2101
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 

Semelhante a 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 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
 
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...
 
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
 

Mais de Mark Papis

Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter KitMark Papis
 
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 missMark Papis
 
Java vs Web security Cheat Sheet
Java vs Web security Cheat SheetJava vs Web security Cheat Sheet
Java vs Web security Cheat SheetMark Papis
 
Java technical stack Cheat Sheet
Java technical stack Cheat SheetJava technical stack Cheat Sheet
Java technical stack Cheat SheetMark Papis
 
Spring cheat sheet
Spring cheat sheetSpring cheat sheet
Spring cheat sheetMark Papis
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetMark Papis
 
Java inheritance cheat sheet
Java inheritance cheat sheetJava inheritance cheat sheet
Java inheritance cheat sheetMark Papis
 
Java Collections comparison Cheat Sheet
Java Collections comparison Cheat SheetJava Collections comparison Cheat Sheet
Java Collections comparison Cheat SheetMark Papis
 

Mais 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
 

Último

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Último (20)

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

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