Java Using Maps v1
Java Using Maps v1
COLLECTIONS FRAMEWORK
COLLECTIONS FRAMEWORK
Indices
0 1 2 3 4 5 6 7 8
A Map
Values
Keys must be
Keys Compass Hat Ball Cards Wand Crystal unique, values
can be repeated
Map Methods
MAP
Map methods:
Map has 25 methods in Java 8,
•containsKey(), and we’ll cover these here.
•containsValue()
•entrySet(),
•forEach()
•get()
•keySet()
•put()
•putAll()
•remove()
•replace()
•size()
•values()
...and more!
The Map Interface
•TreeMap
•LinkedHashMap
Initializing a Map
Our Map will store the names of some programming languages as
keys and the number of courses in our catalog as values.
Map<String,
Map String, Integer>
Integer coursesByLanguage = new HashMap<>();
HashMap<>
...but using a general Map on the left lets us switch out the type
of Map we use on the right without changing any other code!
key value
System.out.println(languagesCount.size());
Console output
> 3
Getting elements from a Map with get()
Map<String, Integer> languagesCount = new HashMap<>();
languagesCount.put("HTML", 5);
languagesCount.put("CSS", 3);
languagesCount.put("JavaScript", 20);
Console output
> Num of HTML courses: 5
Checking if a Map Contains a Certain Key
Map<String, Integer> languagesCount = new HashMap<>();
languagesCount.put("HTML", 5);
languagesCount.put("CSS", 3);
languagesCount.put("JavaScript", 20);
if (languagesCount.containsKey("HTML"))
System.out.print("Yes! We do teach HTML");
else
System.out.print("We do not teach HTML");
Console output
> Yes! We do teach HTML
Iterating through the Map Entries
Console output
Prints each entry’s
> 3 CSS courses value and key in this
5 HTML courses format.
20 JS courses
A Map’s Key Set
Console output
> The languages we teach are: [CSS, JS, HTML]
Summing the Map Values
int sumCourses = 0;
Note that values() returns a
for(Integer value : languagesCount.values()) { List not a Set since the values
sumCourses += value; do not need to be unique.
}
System.out.println("Total courses: " + sumCourses);
Console output
> Total courses: 28
How are the entries
ordered in a Map?
• HashMap - no order is guaranteed
Console output
Elements are added
> 3 CSS courses in sorted order by
5 HTML courses key to the TreeMap
20 JavaScript courses
10 Python courses
LinkedHashMap Preserves Insertion Order
Map<String, Integer> languagesCount = new LinkedHashMap<>();
languagesCount.put("Python", 10);
languagesCount.put("HTML", 5); Notice these are not
languagesCount.put("CSS", 3); added in sorted order
languagesCount.put("JavaScript", 20);
Console output
> 10 Python courses Elements are in the
order in which they
5 HTML courses were added
3 CSS courses
20 JavaScript courses