0% found this document useful (0 votes)
43 views

Java Using Maps v1

The document discusses Java Maps and how they are used to store key-value pairs. Maps allow retrieval of values using their associated keys. The document covers initializing Maps using implementations like HashMap, adding key-value pairs using put(), retrieving values using get(), checking for keys using containsKey(), iterating over entries, and getting the key set or values. The order of elements in a Map depends on the specific implementation, with LinkedHashMap preserving insertion order and TreeMap sorting by keys.

Uploaded by

Milos Mihajlovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Java Using Maps v1

The document discusses Java Maps and how they are used to store key-value pairs. Maps allow retrieval of values using their associated keys. The document covers initializing Maps using implementations like HashMap, adding key-value pairs using put(), retrieving values using get(), checking for keys using containsKey(), iterating over entries, and getting the key set or values. The order of elements in a Map depends on the specific implementation, with LinkedHashMap preserving insertion order and TreeMap sorting by keys.

Uploaded by

Milos Mihajlovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Java Collections: Maps

USING THE MAP INTERFACE

Dr. Sarah Holderness


PLURALSIGHT AUTHOR
@dr_holderness
Assumptions

Basic Java knowledge using interfaces and


inheritance.
– The Collection and Map Interfaces
What this course
– Using a Map
will focus on
– Practical example analyzing Tweets
The Java Collections Framework

COLLECTIONS FRAMEWORK

COLLECTION INTERFACE MAP INTERFACE

LIST SET MAP

An ordered group A group of unique values An unordered group key


of values that are without an index value pairs that are
indexed indexed by a key
numerically
The Java Collections Framework

COLLECTIONS FRAMEWORK

COLLECTION INTERFACE MAP INTERFACE

LIST SET MAP

An ordered group A group of unique values An unordered group key


of values that are without an index value pairs that are
indexed indexed by a key
numerically
Comparing a List to a Map
A List
Values

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

A Map is an Interface, like a Blueprint, that says you MUST


implement these methods to be a Map:
MAP •...
COMPASS: CARDS: •get()
•put()
•putAll()
CRYSTAL BALL: •remove()
•replace()
WAND: HAT: •size()
•values()
...and more!

But we can’t initialize an Interface, so let’s get more specific…


Can We Initialize a Map Yet?

Map<String, Integer> languages = new Map<String, Integer>();

Since Map is ALSO an Interface, we need a non-abstract 



(non-interface) implementation of a Map to initialize.

•Build our own?


•HashMap
•TreeMap
•LinkedHashMap
Can We Initialize a Map Yet?

Map<String, Integer> languages = new Map<String, Integer>();

Since Map is ALSO an Interface, we need a non-abstract 



(non-interface) implementation of a Map to initialize.

•Build our own?


Let’s start with a HashMap -
•HashMap one of the most common Maps used

•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, Integer> coursesByLanguage = new HashMap<>();


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<>

General Map What’s in Specific type Leave type out


Interface the Map of Map here, it’s inferred
Initializing a Map
If we declare our variable as a Map instead HashMap, we can easily
change the specific kind of Map as needed.

HashMap<String, Integer> languages = new HashMap<>();


HashMap HashMap

This is not wrong…

...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!

Using a general Map on


Map<String, Integer> languages = new TreeMap
Map TreeMap<>(); the left is more flexible

Map<String, Integer> languages = new MyMap<>();


Map MyMap
Maps Can Hold any Types of Keys and Values
Map of Integer keys and String values
Map<Integer, String> ssn = new HashMap<>();

Map of String keys and objects of class MyProduct values


Map<String, MyProduct> products = new HashMap<>();

Map of Integer key and List of Strings value

Map<Integer, List<String>> tweets = new HashMap<>();


Adding elements to a Map with put()

Map<String, Integer> languagesCount = new HashMap<>();


languagesCount.put("HTML", 5);
languagesCount.put("CSS", 3);
languagesCount.put("JavaScript", 20);

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);

System.out.println("Num of HTML courses: ", languagesCount.get("HTML"));

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

key "HTML" "CSS" "JS"


value 5 3 20

A Map.Entry is an entrySet() returns a Set of the


individual key/value pair key/value Entries used for iterating

for(Map.Entry<String, Integer> entry : languagesCount.entrySet()) {


System.out.format("%d %s courses%n", entry.getValue(), entry.getKey());
}

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

key "HTML" "CSS" "JS"


value 5 3 20

System.out.println("The languages we teach are: " + languagesCount.keySet());

Note that keySet() returns a


Set and Sets have unique
values. This is possible since
Map keys must also be unique.

Console output
> The languages we teach are: [CSS, JS, HTML]
Summing the Map Values

key "HTML" "CSS" "JS"


value 5 3 20

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

Order Depends on • LinkedHashMap - insertion order


is preserved
the Type of Map
• TreeMap - elements are in sorted
order by key
TreeMap Keys are Sorted
Map<String, Integer> languagesCount = new TreeMap<>();
languagesCount.put("Python", 10);
languagesCount.put("HTML", 5); Notice these are not
languagesCount.put("CSS", 3); added in sorted order
languagesCount.put("JavaScript", 20);

for(Map.Entry<String, Integer> entry : languagesCount.entrySet())


System.out.format("%d %s courses%n", entry.getValue(), entry.getKey());

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);

for(Map.Entry<String, Integer> entry : languagesCount.entrySet())


System.out.format("%d %s courses%n", entry.getValue(), entry.getKey());

Console output
> 10 Python courses Elements are in the
order in which they
5 HTML courses were added
3 CSS courses
20 JavaScript courses

You might also like