SlideShare a Scribd company logo
1 of 42
Collections and Queries
Associative Arrays, Lambda and Stream API
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
sli.do
#fund-java
Questions?
2
Table of Contents
1. Associative Arrays
 HashMap <key, value>
 LinkedHashMap <key, value>
 TreeMap <key, value>
2. Lambda
3. Stream API
 Filtering
 Mapping
 Ordering
Associative Arrays
Collection of Key and Value Pairs
 Associative arrays are arrays indexed by keys
 Not by the numbers 0, 1, 2, … (like arrays)
 Hold a set of pairs {key  value}
Associative Arrays (Maps)
5
John Smith +1-555-8976
Lisa Smith +1-555-1234
Sam Doe +1-555-5030
Key Value
Collections of Key and Value Pairs
 HashMap<K, V>
 Keys are unique
 Uses a hash-table + list
 LinkedHashMap<K, V>
 Keys are unique
 Keeps the keys in order of addition
 TreeMap<K, V>
 Keys are unique
 Keeps its keys always sorted
 Uses a balanced search tree
6
 put(key, value) method
 remove(key) method
HashMap<String, Integer> airplanes = new HashMap<>();
airplanes.put("Boeing 737", 130);
airplanes.put("Airbus A320", 150);
Built-In Methods
7
HashMap<String, Integer> airplanes = new HashMap<>();
airplanes.put("Boeing 737", 130);
airplanes.remove("Boeing 737");
 containsKey(key)
 containsValue(value)
HashMap<String, Integer> map = new HashMap<>();
map.put("Airbus A320", 150);
if (map.containsKey("Airbus A320"))
System.out.println("Airbus A320 key exists");
Built-In methods (2)
8
HashMap<String, Integer> map = new HashMap<>();
map.put("Airbus A320", 150);
System.out.println(map.containsValue(150)); //true
System.out.println(map.containsValue(100)); //false
HashMap: put()
9
HashMap<String, String>
Key Value
Hash Function
Pesho 0881-123-987
Gosho 0881-123-789
Alice 0881-123-978
HashMap: remove()
10
HashMap<String, String>
Key Value
Pesho Pesho
Gosho
0881-123-987
0881-123-789
Alice 0881-123-978Hash Function
Pesho 0881-123-987
TreeMap<K, V> – Example
11
TreeMap
<String, String>
Key Value
Alice +359-899-55-592
Comparator
Function
 Iterate through objects of type Map.Entry<K, V>
 Cannot modify the collection (read-only)
Map<String, Double> fruits = new LinkedHashMap<>();
fruits.put("banana", 2.20);
fruits.put("kiwi", 4.50);
for (Map.Entry<K, V> entry : fruits.entrySet()) {
System.out.printf("%s -> %.2f%n",
entry.getKey(), entry.getValue());
}
Iterating Through Map
12
entry.getKey() -> fruit name
entry.getValue() -> fruit price
 Read a list of real numbers and print them in ascending order
along with their number of occurrences
Problem: Count Real Numbers
13
8 2 2 8 2
2 -> 3
8 -> 2
1 5 1 3
1 -> 2
3 -> 1
5 -> 1
Check your solution here: https://judge.softuni.bg/Contests/1311/
Solution: Count Real Numbers
14
double[] nums = Arrays.stream(sc.nextLine().split(" "))
.mapToDouble(Double::parseDouble).toArray();
Map<Double, Integer> counts = new TreeMap<>();
for (double num : nums) {
if (!counts.containsKey(num))
counts.put(num, 0);
counts.put(num, counts.get(num) + 1);
}
for (Map.Entry<Double, Integer> entry : counts.entrySet()) {
DecimalFormat df = new DecimalFormat("#.#######");
System.out.printf("%s -> %d%n", df.format(entry.getKey()), entry.getValue());
}
Overwrite
the value
Check your solution here: https://judge.softuni.bg/Contests/1311/
 Read 2 * N lines of pairs word and synonym
 Each word may have many synonyms
Problem: Words Synonyms
15
3
cute
adorable
cute
charming
smart
clever
cute - adorable, charming
smart - clever
Check your solution here: https://judge.softuni.bg/Contests/1311/
Solution: Word Synonyms
16
int n = Integer.parseInt(sc.nextLine());
Map<String, ArrayList<String>> words = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
String word = sc.nextLine();
String synonym = sc.nextLine();
words.putIfAbsent(word, new ArrayList<>());
words.get(word).add(synonym);
}
//TODO: Print each word and synonyms
Adding the key if
it does not exist
Check your solution here: https://judge.softuni.bg/Contests/1311/
Lambda Expressions
Anonymous Functions
Lambda Functions
 A lambda expression is an anonymous function containing
expressions and statements
 Lambda expressions
 Use the lambda operator ->
 Read as "goes to"
 The left side specifies the input parameters
 The right side holds the expression or statement
18
(a -> a > 5)
 Lambda functions are inline methods (functions)
that take input parameters and return values:
Lambda Functions
19
x -> x / 2 static int func(int x) { return x / 2; }
static boolean func(int x) { return x != 0; }x -> x != 0
() -> 42 static int func() { return 42; }
Stream API
Traversing and Querying Collections
 min() - finds the smallest element in a collection:
 max() - finds the largest element in a collection:
Processing Arrays with Stream API (1)
21
int min = Arrays.stream(new int[]{15, 25, 35}).min().getAsInt();
int max = Arrays.stream(new int[]{15, 25, 35}).max().getAsInt();
35
int min = Arrays.stream(new int[]{15, 25, 35}).min().orElse(2);
int min = Arrays.stream(new int[]{}).min().orElse(2); // 2
15
 sum() - finds the sum of all elements in a collection:
 average() - finds the average of all elements:
Processing Arrays with Stream API (2)
22
int sum = Arrays.stream(new int[]{15, 25, 35}).sum();
double avg = Arrays.stream(new int[]{15, 25, 35})
.average().getAsDouble();
75
25.0
 min()
Processing Collections with Stream API (1)
23
ArrayList<Integer> nums = new ArrayList<>() {{
add(15); add(25); add(35);
}};
int min = nums.stream().mapToInt(Integer::intValue)
.min().getAsInt();
int min = nums.stream()
.min(Integer::compareTo).get();
15
 max()
 sum()
Processing Collections with Stream API (2)
24
int max = nums.stream().mapToInt(Integer::intValue)
.max().getAsInt();
int max = nums.stream()
.max(Integer::compareTo).get();
int sum = nums.stream()
.mapToInt(Integer::intValue).sum();
35
75
 average()
Processing Collections with Stream API (3)
25
double avg = nums.stream()
.mapToInt(Integer::intValue)
.average()
.getAsDouble(); 25.0
 map() - manipulates elements in a collection:
Manipulating Collections
26
String[] words = {"abc", "def", "geh", "yyy"};
words = Arrays.stream(words)
.map(w -> w + "yyy")
.toArray(String[]::new);
//abcyyy, defyyy, gehyyy, yyyyyy
int[] nums = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(e -> Integer.parseInt(e))
.toArray();
Parse each
element to
Integer
 Using toArray(), toList() to convert collections:
Converting Collections
27
int[] nums = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(e -> Integer.parseInt(e))
.toArray();
List<Integer> nums = Arrays.stream(sc.nextLine()
.split(" "))
.map(e -> Integer.parseInt(e))
.collect(Collectors.toList());
 Using filter()
Filtering Collections
28
int[] nums = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(e -> Integer.parseInt(e))
.filter(n -> n > 0)
.toArray();
 Read a string array
 Print only words which length is even
Problem: Word Filter
29
kiwi orange banana apple
kiwi
orange
banana
pizza cake pasta chips cake
Check your solution here: https://judge.softuni.bg/Contests/1311/
Solution: Word Filter
30
String[] words = Arrays.stream(sc.nextLine().split(" "))
.filter(w -> w.length() % 2 == 0)
.toArray(String[]::new);
for (String word : words) {
System.out.println(word);
}
Check your solution here: https://judge.softuni.bg/Contests/1311/
 Using sorted() to sort collections:
Sorting Collections
31
nums = nums.stream()
.sorted((n1, n2) -> n1.compareTo(n2))
.collect(Collectors.toList());
nums = nums.stream()
.sorted((n1, n2) -> n2.compareTo(n1))
.collect(Collectors.toList());
Ascending (Natural)
Order
Descending
Order
 Using sorted() to sort collections by multiple criteria:
Sorting Collections by Multiple Criteria
32
Map<Integer, String> products = new HashMap<>();
products.entrySet()
.stream()
.sorted((e1, e2) -> {
int res = e2.getValue().compareTo(e1.getValue());
if (res == 0)
res = e1.getKey().compareTo(e2.getKey());
return res; })
.forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
Second criteria
Terminates the stream
Using Functional forEach (1)
33
Map<String, ArrayList<Integer>> arr = new HashMap<>();
arr.entrySet().stream()
.sorted((a, b) -> {
if (a.getKey().compareTo(b.getKey()) == 0) {
int sumFirst = a.getValue().stream().mapToInt(x -> x).sum();
int sumSecond = b.getValue().stream().mapToInt(x -> x).sum();
return sumFirst - sumSecond;
}
return b.getKey().compareTo(a.getKey());
})
Second
criteria
Descending
sorting
Using Functional forEach (2)
34
.forEach(pair -> {
System.out.println("Key: " + pair.getKey());
System.out.print("Value: ");
pair.getValue().sort((a, b) -> a.compareTo(b));
for (int num : pair.getValue()) {
System.out.printf("%d ", num);
}
System.out.println();
});
 Read a list of numbers
 Print largest 3, if there are less than 3, print all of them
Problem: Largest 3 Numbers
35
10 30 15 20 50 5
50 30 20
1 2 3
3 2 1
20 30
30 20
Check your solution here: https://judge.softuni.bg/Contests/1311/
Solution: Largest 3 Numbers
36
List<Integer> nums = Arrays
.stream(sc.nextLine().split(" "))
.map(e -> Integer.parseInt(e))
.sorted((n1, n2) -> n2.compareTo(n1))
.limit(3)
.collect(Collectors.toList());
for (int num : nums) {
System.out.print(num + " ");
}
Check your solution here: https://judge.softuni.bg/Contests/1311/
 …
 …
 …
Summary
 Maps hold {key  value} pairs
 Keyset holds a set of unique keys
 Values hold a collection of values
 Iterating over a map
takes the entries as Map.Entry<K, V>
 Lambda and Stream API help
collection processing
 https://softuni.bg/courses/programming-fundamentals
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
License
42

More Related Content

What's hot

Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Лекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицыЛекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицыMikhail Kurnosov
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplAnkur Shrivastava
 
Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
Лекция 6. Хеш-таблицы
Лекция 6. Хеш-таблицыЛекция 6. Хеш-таблицы
Лекция 6. Хеш-таблицыMikhail Kurnosov
 

What's hot (20)

Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Лекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицыЛекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицы
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
07 java collection
07 java collection07 java collection
07 java collection
 
Threads V4
Threads  V4Threads  V4
Threads V4
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Collection v3
Collection v3Collection v3
Collection v3
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
JDBC
JDBCJDBC
JDBC
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Лекция 6. Хеш-таблицы
Лекция 6. Хеш-таблицыЛекция 6. Хеш-таблицы
Лекция 6. Хеш-таблицы
 
Java Collections
Java  Collections Java  Collections
Java Collections
 

Similar to 18. Java associative arrays

Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programmingAlberto Labarga
 
Python_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdfPython_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdfAnonymousUser67
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheetZahid Hasan
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In ScalaKnoldus Inc.
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...CloudxLab
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxvishal choudhary
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data ManagementAlbert Bifet
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data ManipulationChu An
 
Computation of Semi-Magic Squares Generated by Serpentine Matrices
Computation of Semi-Magic Squares Generated by Serpentine MatricesComputation of Semi-Magic Squares Generated by Serpentine Matrices
Computation of Semi-Magic Squares Generated by Serpentine MatricesLossian Barbosa Bacelar Miranda
 

Similar to 18. Java associative arrays (20)

Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Python_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdfPython_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdf
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Scala collections
Scala collectionsScala collections
Scala collections
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
bobok
bobokbobok
bobok
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
 
Programming in R
Programming in RProgramming in R
Programming in R
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
Computation of Semi-Magic Squares Generated by Serpentine Matrices
Computation of Semi-Magic Squares Generated by Serpentine MatricesComputation of Semi-Magic Squares Generated by Serpentine Matrices
Computation of Semi-Magic Squares Generated by Serpentine Matrices
 

More from Intro C# Book

Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 

More from Intro C# Book (20)

Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 

Recently uploaded

PowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxPowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxgalaxypingy
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...kajalverma014
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.krishnachandrapal52
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirtrahman018755
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsMonica Sydney
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtrahman018755
 
75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptxAsmae Rabhi
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查ydyuyu
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...gajnagarg
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdfMatthew Sinclair
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdfMatthew Sinclair
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Roommeghakumariji156
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge GraphsEleniIlkou
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样ayvbos
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查ydyuyu
 

Recently uploaded (20)

PowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxPowerDirector Explination Process...pptx
PowerDirector Explination Process...pptx
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 

18. Java associative arrays

  • 1. Collections and Queries Associative Arrays, Lambda and Stream API Software University http://softuni.bg SoftUni Team Technical Trainers
  • 3. Table of Contents 1. Associative Arrays  HashMap <key, value>  LinkedHashMap <key, value>  TreeMap <key, value> 2. Lambda 3. Stream API  Filtering  Mapping  Ordering
  • 4. Associative Arrays Collection of Key and Value Pairs
  • 5.  Associative arrays are arrays indexed by keys  Not by the numbers 0, 1, 2, … (like arrays)  Hold a set of pairs {key  value} Associative Arrays (Maps) 5 John Smith +1-555-8976 Lisa Smith +1-555-1234 Sam Doe +1-555-5030 Key Value
  • 6. Collections of Key and Value Pairs  HashMap<K, V>  Keys are unique  Uses a hash-table + list  LinkedHashMap<K, V>  Keys are unique  Keeps the keys in order of addition  TreeMap<K, V>  Keys are unique  Keeps its keys always sorted  Uses a balanced search tree 6
  • 7.  put(key, value) method  remove(key) method HashMap<String, Integer> airplanes = new HashMap<>(); airplanes.put("Boeing 737", 130); airplanes.put("Airbus A320", 150); Built-In Methods 7 HashMap<String, Integer> airplanes = new HashMap<>(); airplanes.put("Boeing 737", 130); airplanes.remove("Boeing 737");
  • 8.  containsKey(key)  containsValue(value) HashMap<String, Integer> map = new HashMap<>(); map.put("Airbus A320", 150); if (map.containsKey("Airbus A320")) System.out.println("Airbus A320 key exists"); Built-In methods (2) 8 HashMap<String, Integer> map = new HashMap<>(); map.put("Airbus A320", 150); System.out.println(map.containsValue(150)); //true System.out.println(map.containsValue(100)); //false
  • 9. HashMap: put() 9 HashMap<String, String> Key Value Hash Function Pesho 0881-123-987 Gosho 0881-123-789 Alice 0881-123-978
  • 10. HashMap: remove() 10 HashMap<String, String> Key Value Pesho Pesho Gosho 0881-123-987 0881-123-789 Alice 0881-123-978Hash Function
  • 11. Pesho 0881-123-987 TreeMap<K, V> – Example 11 TreeMap <String, String> Key Value Alice +359-899-55-592 Comparator Function
  • 12.  Iterate through objects of type Map.Entry<K, V>  Cannot modify the collection (read-only) Map<String, Double> fruits = new LinkedHashMap<>(); fruits.put("banana", 2.20); fruits.put("kiwi", 4.50); for (Map.Entry<K, V> entry : fruits.entrySet()) { System.out.printf("%s -> %.2f%n", entry.getKey(), entry.getValue()); } Iterating Through Map 12 entry.getKey() -> fruit name entry.getValue() -> fruit price
  • 13.  Read a list of real numbers and print them in ascending order along with their number of occurrences Problem: Count Real Numbers 13 8 2 2 8 2 2 -> 3 8 -> 2 1 5 1 3 1 -> 2 3 -> 1 5 -> 1 Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 14. Solution: Count Real Numbers 14 double[] nums = Arrays.stream(sc.nextLine().split(" ")) .mapToDouble(Double::parseDouble).toArray(); Map<Double, Integer> counts = new TreeMap<>(); for (double num : nums) { if (!counts.containsKey(num)) counts.put(num, 0); counts.put(num, counts.get(num) + 1); } for (Map.Entry<Double, Integer> entry : counts.entrySet()) { DecimalFormat df = new DecimalFormat("#.#######"); System.out.printf("%s -> %d%n", df.format(entry.getKey()), entry.getValue()); } Overwrite the value Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 15.  Read 2 * N lines of pairs word and synonym  Each word may have many synonyms Problem: Words Synonyms 15 3 cute adorable cute charming smart clever cute - adorable, charming smart - clever Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 16. Solution: Word Synonyms 16 int n = Integer.parseInt(sc.nextLine()); Map<String, ArrayList<String>> words = new LinkedHashMap<>(); for (int i = 0; i < n; i++) { String word = sc.nextLine(); String synonym = sc.nextLine(); words.putIfAbsent(word, new ArrayList<>()); words.get(word).add(synonym); } //TODO: Print each word and synonyms Adding the key if it does not exist Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 18. Lambda Functions  A lambda expression is an anonymous function containing expressions and statements  Lambda expressions  Use the lambda operator ->  Read as "goes to"  The left side specifies the input parameters  The right side holds the expression or statement 18 (a -> a > 5)
  • 19.  Lambda functions are inline methods (functions) that take input parameters and return values: Lambda Functions 19 x -> x / 2 static int func(int x) { return x / 2; } static boolean func(int x) { return x != 0; }x -> x != 0 () -> 42 static int func() { return 42; }
  • 20. Stream API Traversing and Querying Collections
  • 21.  min() - finds the smallest element in a collection:  max() - finds the largest element in a collection: Processing Arrays with Stream API (1) 21 int min = Arrays.stream(new int[]{15, 25, 35}).min().getAsInt(); int max = Arrays.stream(new int[]{15, 25, 35}).max().getAsInt(); 35 int min = Arrays.stream(new int[]{15, 25, 35}).min().orElse(2); int min = Arrays.stream(new int[]{}).min().orElse(2); // 2 15
  • 22.  sum() - finds the sum of all elements in a collection:  average() - finds the average of all elements: Processing Arrays with Stream API (2) 22 int sum = Arrays.stream(new int[]{15, 25, 35}).sum(); double avg = Arrays.stream(new int[]{15, 25, 35}) .average().getAsDouble(); 75 25.0
  • 23.  min() Processing Collections with Stream API (1) 23 ArrayList<Integer> nums = new ArrayList<>() {{ add(15); add(25); add(35); }}; int min = nums.stream().mapToInt(Integer::intValue) .min().getAsInt(); int min = nums.stream() .min(Integer::compareTo).get(); 15
  • 24.  max()  sum() Processing Collections with Stream API (2) 24 int max = nums.stream().mapToInt(Integer::intValue) .max().getAsInt(); int max = nums.stream() .max(Integer::compareTo).get(); int sum = nums.stream() .mapToInt(Integer::intValue).sum(); 35 75
  • 25.  average() Processing Collections with Stream API (3) 25 double avg = nums.stream() .mapToInt(Integer::intValue) .average() .getAsDouble(); 25.0
  • 26.  map() - manipulates elements in a collection: Manipulating Collections 26 String[] words = {"abc", "def", "geh", "yyy"}; words = Arrays.stream(words) .map(w -> w + "yyy") .toArray(String[]::new); //abcyyy, defyyy, gehyyy, yyyyyy int[] nums = Arrays.stream(sc.nextLine().split(" ")) .mapToInt(e -> Integer.parseInt(e)) .toArray(); Parse each element to Integer
  • 27.  Using toArray(), toList() to convert collections: Converting Collections 27 int[] nums = Arrays.stream(sc.nextLine().split(" ")) .mapToInt(e -> Integer.parseInt(e)) .toArray(); List<Integer> nums = Arrays.stream(sc.nextLine() .split(" ")) .map(e -> Integer.parseInt(e)) .collect(Collectors.toList());
  • 28.  Using filter() Filtering Collections 28 int[] nums = Arrays.stream(sc.nextLine().split(" ")) .mapToInt(e -> Integer.parseInt(e)) .filter(n -> n > 0) .toArray();
  • 29.  Read a string array  Print only words which length is even Problem: Word Filter 29 kiwi orange banana apple kiwi orange banana pizza cake pasta chips cake Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 30. Solution: Word Filter 30 String[] words = Arrays.stream(sc.nextLine().split(" ")) .filter(w -> w.length() % 2 == 0) .toArray(String[]::new); for (String word : words) { System.out.println(word); } Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 31.  Using sorted() to sort collections: Sorting Collections 31 nums = nums.stream() .sorted((n1, n2) -> n1.compareTo(n2)) .collect(Collectors.toList()); nums = nums.stream() .sorted((n1, n2) -> n2.compareTo(n1)) .collect(Collectors.toList()); Ascending (Natural) Order Descending Order
  • 32.  Using sorted() to sort collections by multiple criteria: Sorting Collections by Multiple Criteria 32 Map<Integer, String> products = new HashMap<>(); products.entrySet() .stream() .sorted((e1, e2) -> { int res = e2.getValue().compareTo(e1.getValue()); if (res == 0) res = e1.getKey().compareTo(e2.getKey()); return res; }) .forEach(e -> System.out.println(e.getKey() + " " + e.getValue())); Second criteria Terminates the stream
  • 33. Using Functional forEach (1) 33 Map<String, ArrayList<Integer>> arr = new HashMap<>(); arr.entrySet().stream() .sorted((a, b) -> { if (a.getKey().compareTo(b.getKey()) == 0) { int sumFirst = a.getValue().stream().mapToInt(x -> x).sum(); int sumSecond = b.getValue().stream().mapToInt(x -> x).sum(); return sumFirst - sumSecond; } return b.getKey().compareTo(a.getKey()); }) Second criteria Descending sorting
  • 34. Using Functional forEach (2) 34 .forEach(pair -> { System.out.println("Key: " + pair.getKey()); System.out.print("Value: "); pair.getValue().sort((a, b) -> a.compareTo(b)); for (int num : pair.getValue()) { System.out.printf("%d ", num); } System.out.println(); });
  • 35.  Read a list of numbers  Print largest 3, if there are less than 3, print all of them Problem: Largest 3 Numbers 35 10 30 15 20 50 5 50 30 20 1 2 3 3 2 1 20 30 30 20 Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 36. Solution: Largest 3 Numbers 36 List<Integer> nums = Arrays .stream(sc.nextLine().split(" ")) .map(e -> Integer.parseInt(e)) .sorted((n1, n2) -> n2.compareTo(n1)) .limit(3) .collect(Collectors.toList()); for (int num : nums) { System.out.print(num + " "); } Check your solution here: https://judge.softuni.bg/Contests/1311/
  • 37.  …  …  … Summary  Maps hold {key  value} pairs  Keyset holds a set of unique keys  Values hold a collection of values  Iterating over a map takes the entries as Map.Entry<K, V>  Lambda and Stream API help collection processing
  • 41.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 42.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license License 42

Editor's Notes

  1. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  2. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
  3. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.