SlideShare a Scribd company logo
Meeting 8: Sets and Maps
Edited by: Dr. Bayan Abu Shawar
AOU-Jordan
2
Objectives
 To store unordered, non-duplicate elements using a set.
 To explore how and when to use HashSet, LinkedHashSet, or
TreeSet to store elements.
 To compare performance of sets and lists.
 To tell the differences between Collection and Map and describe
when and how to use HashMap, LinkedHashMap, and TreeMap
to store values associated with keys.
3
Motivations
The “No-Fly” list is a list, created and maintained by the
U.S. government’s Terrorist Screening Center, of people
who are not permitted to board a commercial aircraft for
travel in or out of the United States. Suppose we need to
write a program that checks whether a person is on the
No-Fly list. You can use a list to store names in the No-
Fly list. However, a more efficient data structure for this
application is a set.
Suppose your program also needs to store detailed information
about terrorists in the No-Fly list. The detailed information
such as gender, height, weight, and nationality can be retrieved
using the name as the key. A map is an efficient data structure
for such a task.
Collection FrameWork
The Collection FrameWork
The Collections Framework unifies the
collection classes. It contains two root
interfaces, Collection and Map.
Set, List, and Queue is a subinterface of
Collection.
Arrays are not part of the Collections
Framework, as they do not implement
either the Collection or Map interfaces.
6
Review of Java Collection
Framework hierarchy
Set and List are subinterfaces of Collection.
The Collection interfaces
The Collection interface is the root interface for
manipulating a collection of objects: Set, List,
Queue.
The Collections Framework does three things:
 It specifies a set of collection interfaces
 recommends some constructors for the classes that
implement them;
 provides some utility classes.
These, together with collection classes meeting
these specifications are said to constitute the
Collections Framework.
An Interface
As you studied before, an interface is
essentially a list of methods without any
actual implementation.
Any concrete class that implements an
interface must understand all the
messages associated with the methods in
the interface, either by implementing the
methods or inheriting them from a
superclass.
Collection Interface
The Collection interface is a superinterface of the
collection interfaces: Set, List, and Queue. All of the
methods in Collection are inherited by the interfaces Set,
List, Queue, etc. The Collection interface specifies
methods such as add(), size() and isEmpty(), which are
common to very many kinds of collection.
In order to use any Collection type, You need to:
import java.util.*;
10
Iterator-Interface
This interface allows traversing / iterating through any collection, such
as Set, an ArrayList, etc.
The following abstract methods are defined for any class that
implements the iterator:
 boolean hasNext(): returns true if the iteration has more elements
 E next(): returns the next element in the iteration(E is the type the
interface is implemented for)
 void remove() : removes from the underlying collection the last
element returned by the iterator; note that it is important to precede
any call to remove() by a call to next().
Iterator Interface
Note that it is possible to declare a variable of an interface type.
 any class that implements the Iterator interface may be referenced by such
a variable.
ArrayList<String> X = new ArrayList<String>();
........
Iterator<String> listX = X.iterator();
while (listX.hasNext())
System.out.print( listX.next() + " , ");
Some of Collection Interface
Methods
The Set Interface
 A set is a not ordered collection in which every element is unique
(i.e. there are no duplicates). A set can grow and shrink as elements
are added or removed (dynamic size). The contents of a set are not
indexed, so we have no way of reaching a particular item except by
stepping through the elements until we come to the one we want.
 The most general kind of set is unordered, although we will see that
 ordered sets also exist.
 You should think of a set as a pool of objects, none of which can
appear twice, and we can add things to the pool or remove them as
we please.
15
The Set Interface
The Set interface extends the Collection
interface. It does not introduce new methods or
constants, but it stipulates that an instance of
Set contains no duplicate elements.
The concrete classes that implement Set must
ensure that no duplicate elements can be added
to the set. That is no two elements e1 and e2
can be in the set such that e1.equals(e2) is true.
16
The Set Interface
Hierarchy
Creating a Set
Whenever we use any kind of collection from the Java Collections
Framework there are three things we must do first:
1. Decide on the interface type. What protocol do we want to use with
our collection? Interface Set
2. Choose an implementation class. That is, what class will the actual
collection belong to? Implementation class: HashSet
3. Declare an element type. What data type will the collection contain?
A set of String, Integer, Doubles, etc, the element type should be a
reference type not primitive the same as ArrayList.
HasheSet, TreeSet, &
LinkedHashSet
You can declare an object of
Set<Element_Type> collection, and create
it using any of the below concrete classes:
HashSet doesn’t maintain any kind of order of its
elements.
TreeSet sorts the elements in ascending order.
LinkedHashSet maintains the insertion order.
Declaring and creating a variable to reference a
set for holding strings
Declaration
Creation
Decaring and Creatng a Set
Collection
Collection Interface<E> name = new CocreteClass<E>();
Set <String> set1 = new HashSet <String>(); OR
HashSet<String> set1 = new HashSet <String>();
Set <Double> set2 = new HashSet <double> (10);
Set<String> Set3 = new HashSet <String>(set1);
//The above statement will copy set1 to set3
Set <String> set4 = new TreeSet<String>(set1);
//set4 will have the same content of set3 but in ascending order.
capacity
Another
collection
21
The HashSet Class
The HashSet class is a concrete class that
implements Set.
For efficiency, objects added to a hash set
need to implement the hashCode method in
a manner that properly disperses the hash
code.
HashSet<E>()
HashSet<E>(c: Collection<E>)
22
The SortedSet Interface and the
TreeSet Class
SortedSet is a subinterface of Set, which
guarantees that the elements in the set are
sorted.
TreeSet is a concrete class that implements
the SortedSet interface. You can use an
iterator to traverse the elements in the sorted
order.
TreeSet<E>()
TreeSet<E>(c: Collection<E>)
LinkedHashSet Class
LinkedHashSet maintains the insertion
order. Elements gets sorted in the same
sequence in which they have been added
to the Set.
LinkedHashSet<E>();
LinkedHashSet<E>(c: Collection<E>);
Some of the methods specified by
the Set interface
Iterating over a Set
You can iterate over a Set using:
For-each statement
Using iterator
For-each statement
public static void main(String[] args) {
// Create a hash set
Set<String> set = new HashSet<String>();
// Add strings to the set
set.add("London"); set.add("Paris"); set.add("New York");
set.add("San Francisco");
set.add("Beijing"); set.add("New York");
System.out.println(set);
// Display the elements in the hash set
for (String s: set)
System.out.print(s.toUpperCase() + " ");
}
Exercise(1)
Write Java code to do the followings:
Create a set of strings with each element
being the name of a herb.
Add the following herbs: Rosemary,
Parsely, Camomile, Rosemary.
Print out the size of the set
Print the set
Solution of Exercise(1)
Set<String> herbSet = new HashSet<String>();
herbSet.add("Rosemary");
herbSet.add("Parsely");
herbSet.add(“Camomile");
herbSet.add("Rosemary");
System.out.println(herbSet.size());
System.out.println(herbSet);
TreeSet Class
Suppose we wanted to have the herbs printed out
alphabetically. In this case you need to use
TreeSet, which does have order.
All we need to do is alter
Set<String> set = new HashSet<String>();
to
Set<String> set = new TreeSet<String>();
The herbs will now automatically be in order.
30
Case Study: Counting Keywords
This section presents an application that
counts the number of the keywords in a Java
source file.
Run
CountKeywords
Bulk Operations on Set Interface
The interface Set defines several useful bulk operations; that is,
operations that involve every element in one or more sets. Below
are some of the bulk Operations : Let us assume that set1 and set2
reference instances of classes that implement Set.
 set1.containsAll(set2);
Answers true if set1 contains all the elements in set2.
 set1.addAll(set2); //set1 = set1 Union set2
Adds all of the elements in set2 to set1, if they are not already present,
answering true if set1 was altered. Union between two sets
 set1.retainAll(set2); set1 = set1 intersect set2
Retains any elements set1 has in common with set2, answering true if set1
was changed. Intersection between two sets
 set1.removeAll(set2); //set1 = set1 – set2
Removes any elements from set1 that set1 has in common with set2,
answering true if set1 was changed. Set difference
Bulk Operations on Set Interface
 Operations that alter the contents of the receiver are
referred to as destructive operations, whereas those that
do not are referred to as nondestructive operations.
 The bulk methods retainAll(), addAll() and removeAll()
correspond to the set operations known as intersection,
union and set difference. These methods are destructive
– they alter the original set – so it is normally best to
work with a copy.
Exercise(2)
Create two linked Hash sets {3,4,5,2,1}, and
{2,3,7,8,9} . Find and print their union,
intersection, and difference. You need to
print the original sets first.
Solution of Exercise(2)
public static void main(String[] args) {
Integer[] a1 = {3,4,5,2,1};
Integer[] a2 = {2,3,7,8,9};
List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(a1));
List<Integer> l2 = new ArrayList<Integer>(Arrays.asList(a2));
Set<Integer> s1 = new LinkedHashSet<Integer>(l1);
Set<Integer> s2 = new LinkedHashSet<Integer>(l2);
Set<Integer> union = new LinkedHashSet<Integer>(s1);
Set<Integer> intersect = new LinkedHashSet<Integer>(s1);
Set<Integer> difference = new LinkedHashSet<Integer>(s1);
System.out.println("s1: "+ s1);
System.out.println("s2: "+ s2);
difference.removeAll(s2);
System.out.println("s1-s2 = "+ difference);
union.addAll(s2);
System.out.println("s1 union s2 = "+ union);
intersect.retainAll(s2);
System.out.println("s1 intersects s2 = "+ intersect);
}
Map Interface
A Map Interface stores pairs of linked
items in key–value pairs known as entries.
It looks like a table wherein the key should
be unique.
Maps are dynamically sized, indexed by
keys and do not allow duplicate keys. The
elements are unordered.
36
The Map Interface
The Map interface maps keys to the elements. The
keys are like indexes. In List, the indexes are
integer. In Map, the keys can be any objects.
37
Map Interface and Class Hierarchy
An instance of Map represents a group of objects,
each of which is represented as key-value. You can
get the object from a map using a key, and you
have to use a key to put the object into the map.
38
The Map Interface UML Diagram
Some of the Methods of the Map Interface
40
Concrete Map Classes
Concrete classes to implement Map
Interface
There are three concrete classes that
implements Map interface:
HashMap: is implemented as a hash table, and
there is no ordering on keys or values.
TreeMap: is implemented based on red-black
tree structure, and it is ordered by the key.
LinkedHashMap: inherits HashMap, and is
implemented as linked list that maintains the
insertion order.
Declare and create a Map
How to declare a HashMap?
Similar to ArrayList, and Set but with the types of both the
key and value.
Map <String,String> table1 = new HashMap <String,String>(); OR
HashMap <String,String> table1 = new HashMap <String,String>();
Map <String,Double> table2 = new HashMap <String,double> (10);
Map <String,String> table3 = new HashMap <String,String>(table1);
//The above statement will copy table1 to table 3
Map <String,String> table4 = new TreeMap <String,String>(table1);
//table4 will have the same content of able 3 but in ascending order based
on the key.
Capacity
Another
Map
Traversing Map Collection
You can use for each statement to iterate a
Map row by row.
For(Key_Type variable: Map_Name.keySet()){
//the key is stored in variable, to obtain the value use
//Map_name.get(variable)
}
Example:
for(String x : table 1.keySet())
System.out.println(x+” “+ table1.get(x)
44
Exercise(3): Using HashMap and
TreeMap
This exercise creates a hash map that maps names to their
ages.
The program first creates a hash map with the name as its key and
age as its value: (“Smith”,30), (“Anderson", 31), (“Lewis", 29), and
("Cook", 29). Then display the content.
Print out the names whose age are greater than or equal to 30.
Print out the age of Lewis
The program then creates a tree map from the hash map, and
displays the mappings in ascending order of the keys.
Run
TestMap
Exercise(3)_Solution
public class TestMap {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("Smith", 30); hashMap.put("Anderson", 31);
hashMap.put("Lewis", 29);
hashMap.put("Cook", 29);
System.out.println("Display entries in HashMap");
System.out.println(hashMap + "n");
System.out.println("nThe age for " + "Lewis is " + hashMap.get("Lewis"));
System.out.println("Names for those whose ag >= 30 are: ");
for(String s: hashMap.keySet())
if(hashMap.get(s) >= 30)
System.out.println(s+" "+ hashMap.get(s));
Continue-Exercise(3)_Solution
// Create a TreeMap from the preceding HashMap
Map<String, Integer> treeMap = new TreeMap<String, Integer>(hashMap);
System.out.println("Display entries in ascending order of key");
System.out.println(treeMap);
}
}// end class
47
Exercise(4): Counting the Occurrences of
Words in a String
Write Java program to count the occurrences of words
in a text and displays the words and their occurrences in
ascending order of the words. Assume text is:
"Good morning. Have a good class. " + "Have a good
visit. Have fun!"
The program uses a hash map to store a pair
consisting of a word and its count. For each word, check
whether it is already a key in the map. If not, add the key
and value 1 to the map. Otherwise, increase the value
for the word (key) by 1 in the map.
Display the content of the Map.
Run
CountOccurrenceOfWords
Solution of Exercise(4)
import java.util.*;
public class CountOccurrenceOfWords {
public static void main(String[] args) {
String text = "Good morning. Have a good class. " + "Have a good visit. Have fun!";
Map<String, Integer> map = new TreeMap<String, Integer>();
String[] words = text.split("W+"); // split text into words , this mean the delimiter
will be anything that is not a word.
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase();
if (key.length() > 0) {
if (!map.containsKey(key))
map.put(key, 1);
else {
int value = map.get(key);
value++;
map.put(key, value); }
}
} //for
Continue Solution of Exercise(4)
System.out.println(“Words t Count”);
System.out.println(“----------------------------”);
for(String t : map.keySet())
System.out.println(t+”t“+ map.get(t));
}//main
}//class
Important Notes
 The Collection Framework has two rooted interfaces:
Collection, and Map.
 Set, List, and Queue are sub-Interfaces from Collection
Interface.
 Distinguish between Collection Interface, and the
Collections class that is used to do some operations on
the ArrayList such as: reverse, sort, etc as you studied in
Meeting6.
 You did not use Collection Interface methods directly,
you use its sub-Interfaces to declare objects of Set, List,
or Queue then use objects to onvoke methods. Wherein
Collections class methods are used using Collections
class to invoke methods: Collections.sort(x), etc.
Please solve the Activity of Meeting 8.

More Related Content

Similar to M251_Meeting 8 (Sets and Maps_Java_).ppt (20)

PPTX
Java.util
Ramakrishna kapa
 
PPT
description of Collections, seaching & Sorting
mdimberu
 
PPTX
Presentation1
Anand Grewal
 
PPTX
22CS305-UNIT-1.pptx ADVANCE JAVA PROGRAMMING
logesswarisrinivasan
 
PDF
Array list (java platform se 8 )
charan kumar
 
PPTX
oop lecture framework,list,maps,collection
ssuseredfbe9
 
DOCX
Collections generic
sandhish
 
PPT
11000121065_NAITIK CHATTERJEE.ppt
NaitikChatterjee
 
PPTX
Collections
sagsharma
 
PDF
Java collections
padmad2291
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPTX
collection framework.pptx
SoniaKapoor56
 
PDF
Collections Api - Java
Drishti Bhalla
 
PPT
20 ch22 collections
Abhijit Gaikwad
 
PPTX
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
DOCX
Collections framework
Anand Buddarapu
 
PDF
A04
lksoo
 
PPTX
Data structures in c#
SivaSankar Gorantla
 
PPTX
Array list(1)
abdullah619
 
Java.util
Ramakrishna kapa
 
description of Collections, seaching & Sorting
mdimberu
 
Presentation1
Anand Grewal
 
22CS305-UNIT-1.pptx ADVANCE JAVA PROGRAMMING
logesswarisrinivasan
 
Array list (java platform se 8 )
charan kumar
 
oop lecture framework,list,maps,collection
ssuseredfbe9
 
Collections generic
sandhish
 
11000121065_NAITIK CHATTERJEE.ppt
NaitikChatterjee
 
Collections
sagsharma
 
Java collections
padmad2291
 
Collections in Java Notes
Shalabh Chaudhary
 
collection framework.pptx
SoniaKapoor56
 
Collections Api - Java
Drishti Bhalla
 
20 ch22 collections
Abhijit Gaikwad
 
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
Collections framework
Anand Buddarapu
 
A04
lksoo
 
Data structures in c#
SivaSankar Gorantla
 
Array list(1)
abdullah619
 

More from smartashammari (20)

PPT
M251_Meeting 8 (SetsandMap Advanced Java).ppt
smartashammari
 
PPT
M251_Meeting 9 (Recursion_AdvancedJava).ppt
smartashammari
 
PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
PPT
M251_Meeting 7 (Exception Handling and Text IO).ppt
smartashammari
 
PPT
SLoSP-2007-1statisticalstatisticalstatistical.ppt
smartashammari
 
PPTX
1introduction-191021211508Algorithms and data structures.pptx
smartashammari
 
PPT
carrano_ppt04Algorithims and data structures.ppt
smartashammari
 
PPTX
lecture1-220221114413Algorithims and data structures.pptx
smartashammari
 
PPT
Data Structures: Introduction_______.ppt
smartashammari
 
PPT
DATA MININ _ TECHNOLOGY AND TECHNIQUE.ppt
smartashammari
 
PPTX
oopinpyhtonnew-140722060241-phpapp01.pptx
smartashammari
 
PPT
carrano_ppt04 Data Abstraction: The Walls .ppt
smartashammari
 
PPTX
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
PPT
DSA___________________SSSSSSSSSSSSSS.ppt
smartashammari
 
PPTX
lecture1-2202211144eeeee24444444413.pptx
smartashammari
 
PPT
carrano_ppt04 DSAddddddddddddddddddd.ppt
smartashammari
 
PDF
datavisualizationinpythonv2-171103225436.pdf
smartashammari
 
PPTX
python-numwpyandpandas-170922144956.pptx
smartashammari
 
PPTX
NumPy_ SciPy_ _ DatiiiikaFrames (2).pptx
smartashammari
 
PPTX
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python (3).pptx
smartashammari
 
M251_Meeting 8 (SetsandMap Advanced Java).ppt
smartashammari
 
M251_Meeting 9 (Recursion_AdvancedJava).ppt
smartashammari
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
M251_Meeting 7 (Exception Handling and Text IO).ppt
smartashammari
 
SLoSP-2007-1statisticalstatisticalstatistical.ppt
smartashammari
 
1introduction-191021211508Algorithms and data structures.pptx
smartashammari
 
carrano_ppt04Algorithims and data structures.ppt
smartashammari
 
lecture1-220221114413Algorithims and data structures.pptx
smartashammari
 
Data Structures: Introduction_______.ppt
smartashammari
 
DATA MININ _ TECHNOLOGY AND TECHNIQUE.ppt
smartashammari
 
oopinpyhtonnew-140722060241-phpapp01.pptx
smartashammari
 
carrano_ppt04 Data Abstraction: The Walls .ppt
smartashammari
 
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
DSA___________________SSSSSSSSSSSSSS.ppt
smartashammari
 
lecture1-2202211144eeeee24444444413.pptx
smartashammari
 
carrano_ppt04 DSAddddddddddddddddddd.ppt
smartashammari
 
datavisualizationinpythonv2-171103225436.pdf
smartashammari
 
python-numwpyandpandas-170922144956.pptx
smartashammari
 
NumPy_ SciPy_ _ DatiiiikaFrames (2).pptx
smartashammari
 
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python (3).pptx
smartashammari
 
Ad

Recently uploaded (20)

PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Adobe Premiere Pro Crack / Full Version / Free Download
hashhshs786
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Adobe Premiere Pro Crack / Full Version / Free Download
hashhshs786
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Ad

M251_Meeting 8 (Sets and Maps_Java_).ppt

  • 1. Meeting 8: Sets and Maps Edited by: Dr. Bayan Abu Shawar AOU-Jordan
  • 2. 2 Objectives  To store unordered, non-duplicate elements using a set.  To explore how and when to use HashSet, LinkedHashSet, or TreeSet to store elements.  To compare performance of sets and lists.  To tell the differences between Collection and Map and describe when and how to use HashMap, LinkedHashMap, and TreeMap to store values associated with keys.
  • 3. 3 Motivations The “No-Fly” list is a list, created and maintained by the U.S. government’s Terrorist Screening Center, of people who are not permitted to board a commercial aircraft for travel in or out of the United States. Suppose we need to write a program that checks whether a person is on the No-Fly list. You can use a list to store names in the No- Fly list. However, a more efficient data structure for this application is a set. Suppose your program also needs to store detailed information about terrorists in the No-Fly list. The detailed information such as gender, height, weight, and nationality can be retrieved using the name as the key. A map is an efficient data structure for such a task.
  • 5. The Collection FrameWork The Collections Framework unifies the collection classes. It contains two root interfaces, Collection and Map. Set, List, and Queue is a subinterface of Collection. Arrays are not part of the Collections Framework, as they do not implement either the Collection or Map interfaces.
  • 6. 6 Review of Java Collection Framework hierarchy Set and List are subinterfaces of Collection.
  • 7. The Collection interfaces The Collection interface is the root interface for manipulating a collection of objects: Set, List, Queue. The Collections Framework does three things:  It specifies a set of collection interfaces  recommends some constructors for the classes that implement them;  provides some utility classes. These, together with collection classes meeting these specifications are said to constitute the Collections Framework.
  • 8. An Interface As you studied before, an interface is essentially a list of methods without any actual implementation. Any concrete class that implements an interface must understand all the messages associated with the methods in the interface, either by implementing the methods or inheriting them from a superclass.
  • 9. Collection Interface The Collection interface is a superinterface of the collection interfaces: Set, List, and Queue. All of the methods in Collection are inherited by the interfaces Set, List, Queue, etc. The Collection interface specifies methods such as add(), size() and isEmpty(), which are common to very many kinds of collection. In order to use any Collection type, You need to: import java.util.*;
  • 10. 10
  • 11. Iterator-Interface This interface allows traversing / iterating through any collection, such as Set, an ArrayList, etc. The following abstract methods are defined for any class that implements the iterator:  boolean hasNext(): returns true if the iteration has more elements  E next(): returns the next element in the iteration(E is the type the interface is implemented for)  void remove() : removes from the underlying collection the last element returned by the iterator; note that it is important to precede any call to remove() by a call to next().
  • 12. Iterator Interface Note that it is possible to declare a variable of an interface type.  any class that implements the Iterator interface may be referenced by such a variable. ArrayList<String> X = new ArrayList<String>(); ........ Iterator<String> listX = X.iterator(); while (listX.hasNext()) System.out.print( listX.next() + " , ");
  • 13. Some of Collection Interface Methods
  • 14. The Set Interface  A set is a not ordered collection in which every element is unique (i.e. there are no duplicates). A set can grow and shrink as elements are added or removed (dynamic size). The contents of a set are not indexed, so we have no way of reaching a particular item except by stepping through the elements until we come to the one we want.  The most general kind of set is unordered, although we will see that  ordered sets also exist.  You should think of a set as a pool of objects, none of which can appear twice, and we can add things to the pool or remove them as we please.
  • 15. 15 The Set Interface The Set interface extends the Collection interface. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements. The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.
  • 17. Creating a Set Whenever we use any kind of collection from the Java Collections Framework there are three things we must do first: 1. Decide on the interface type. What protocol do we want to use with our collection? Interface Set 2. Choose an implementation class. That is, what class will the actual collection belong to? Implementation class: HashSet 3. Declare an element type. What data type will the collection contain? A set of String, Integer, Doubles, etc, the element type should be a reference type not primitive the same as ArrayList.
  • 18. HasheSet, TreeSet, & LinkedHashSet You can declare an object of Set<Element_Type> collection, and create it using any of the below concrete classes: HashSet doesn’t maintain any kind of order of its elements. TreeSet sorts the elements in ascending order. LinkedHashSet maintains the insertion order.
  • 19. Declaring and creating a variable to reference a set for holding strings Declaration Creation
  • 20. Decaring and Creatng a Set Collection Collection Interface<E> name = new CocreteClass<E>(); Set <String> set1 = new HashSet <String>(); OR HashSet<String> set1 = new HashSet <String>(); Set <Double> set2 = new HashSet <double> (10); Set<String> Set3 = new HashSet <String>(set1); //The above statement will copy set1 to set3 Set <String> set4 = new TreeSet<String>(set1); //set4 will have the same content of set3 but in ascending order. capacity Another collection
  • 21. 21 The HashSet Class The HashSet class is a concrete class that implements Set. For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code. HashSet<E>() HashSet<E>(c: Collection<E>)
  • 22. 22 The SortedSet Interface and the TreeSet Class SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order. TreeSet<E>() TreeSet<E>(c: Collection<E>)
  • 23. LinkedHashSet Class LinkedHashSet maintains the insertion order. Elements gets sorted in the same sequence in which they have been added to the Set. LinkedHashSet<E>(); LinkedHashSet<E>(c: Collection<E>);
  • 24. Some of the methods specified by the Set interface
  • 25. Iterating over a Set You can iterate over a Set using: For-each statement Using iterator
  • 26. For-each statement public static void main(String[] args) { // Create a hash set Set<String> set = new HashSet<String>(); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println(set); // Display the elements in the hash set for (String s: set) System.out.print(s.toUpperCase() + " "); }
  • 27. Exercise(1) Write Java code to do the followings: Create a set of strings with each element being the name of a herb. Add the following herbs: Rosemary, Parsely, Camomile, Rosemary. Print out the size of the set Print the set
  • 28. Solution of Exercise(1) Set<String> herbSet = new HashSet<String>(); herbSet.add("Rosemary"); herbSet.add("Parsely"); herbSet.add(“Camomile"); herbSet.add("Rosemary"); System.out.println(herbSet.size()); System.out.println(herbSet);
  • 29. TreeSet Class Suppose we wanted to have the herbs printed out alphabetically. In this case you need to use TreeSet, which does have order. All we need to do is alter Set<String> set = new HashSet<String>(); to Set<String> set = new TreeSet<String>(); The herbs will now automatically be in order.
  • 30. 30 Case Study: Counting Keywords This section presents an application that counts the number of the keywords in a Java source file. Run CountKeywords
  • 31. Bulk Operations on Set Interface The interface Set defines several useful bulk operations; that is, operations that involve every element in one or more sets. Below are some of the bulk Operations : Let us assume that set1 and set2 reference instances of classes that implement Set.  set1.containsAll(set2); Answers true if set1 contains all the elements in set2.  set1.addAll(set2); //set1 = set1 Union set2 Adds all of the elements in set2 to set1, if they are not already present, answering true if set1 was altered. Union between two sets  set1.retainAll(set2); set1 = set1 intersect set2 Retains any elements set1 has in common with set2, answering true if set1 was changed. Intersection between two sets  set1.removeAll(set2); //set1 = set1 – set2 Removes any elements from set1 that set1 has in common with set2, answering true if set1 was changed. Set difference
  • 32. Bulk Operations on Set Interface  Operations that alter the contents of the receiver are referred to as destructive operations, whereas those that do not are referred to as nondestructive operations.  The bulk methods retainAll(), addAll() and removeAll() correspond to the set operations known as intersection, union and set difference. These methods are destructive – they alter the original set – so it is normally best to work with a copy.
  • 33. Exercise(2) Create two linked Hash sets {3,4,5,2,1}, and {2,3,7,8,9} . Find and print their union, intersection, and difference. You need to print the original sets first.
  • 34. Solution of Exercise(2) public static void main(String[] args) { Integer[] a1 = {3,4,5,2,1}; Integer[] a2 = {2,3,7,8,9}; List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(a1)); List<Integer> l2 = new ArrayList<Integer>(Arrays.asList(a2)); Set<Integer> s1 = new LinkedHashSet<Integer>(l1); Set<Integer> s2 = new LinkedHashSet<Integer>(l2); Set<Integer> union = new LinkedHashSet<Integer>(s1); Set<Integer> intersect = new LinkedHashSet<Integer>(s1); Set<Integer> difference = new LinkedHashSet<Integer>(s1); System.out.println("s1: "+ s1); System.out.println("s2: "+ s2); difference.removeAll(s2); System.out.println("s1-s2 = "+ difference); union.addAll(s2); System.out.println("s1 union s2 = "+ union); intersect.retainAll(s2); System.out.println("s1 intersects s2 = "+ intersect); }
  • 35. Map Interface A Map Interface stores pairs of linked items in key–value pairs known as entries. It looks like a table wherein the key should be unique. Maps are dynamically sized, indexed by keys and do not allow duplicate keys. The elements are unordered.
  • 36. 36 The Map Interface The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.
  • 37. 37 Map Interface and Class Hierarchy An instance of Map represents a group of objects, each of which is represented as key-value. You can get the object from a map using a key, and you have to use a key to put the object into the map.
  • 38. 38 The Map Interface UML Diagram
  • 39. Some of the Methods of the Map Interface
  • 41. Concrete classes to implement Map Interface There are three concrete classes that implements Map interface: HashMap: is implemented as a hash table, and there is no ordering on keys or values. TreeMap: is implemented based on red-black tree structure, and it is ordered by the key. LinkedHashMap: inherits HashMap, and is implemented as linked list that maintains the insertion order.
  • 42. Declare and create a Map How to declare a HashMap? Similar to ArrayList, and Set but with the types of both the key and value. Map <String,String> table1 = new HashMap <String,String>(); OR HashMap <String,String> table1 = new HashMap <String,String>(); Map <String,Double> table2 = new HashMap <String,double> (10); Map <String,String> table3 = new HashMap <String,String>(table1); //The above statement will copy table1 to table 3 Map <String,String> table4 = new TreeMap <String,String>(table1); //table4 will have the same content of able 3 but in ascending order based on the key. Capacity Another Map
  • 43. Traversing Map Collection You can use for each statement to iterate a Map row by row. For(Key_Type variable: Map_Name.keySet()){ //the key is stored in variable, to obtain the value use //Map_name.get(variable) } Example: for(String x : table 1.keySet()) System.out.println(x+” “+ table1.get(x)
  • 44. 44 Exercise(3): Using HashMap and TreeMap This exercise creates a hash map that maps names to their ages. The program first creates a hash map with the name as its key and age as its value: (“Smith”,30), (“Anderson", 31), (“Lewis", 29), and ("Cook", 29). Then display the content. Print out the names whose age are greater than or equal to 30. Print out the age of Lewis The program then creates a tree map from the hash map, and displays the mappings in ascending order of the keys. Run TestMap
  • 45. Exercise(3)_Solution public class TestMap { public static void main(String[] args) { // Create a HashMap Map<String, Integer> hashMap = new HashMap<String, Integer>(); hashMap.put("Smith", 30); hashMap.put("Anderson", 31); hashMap.put("Lewis", 29); hashMap.put("Cook", 29); System.out.println("Display entries in HashMap"); System.out.println(hashMap + "n"); System.out.println("nThe age for " + "Lewis is " + hashMap.get("Lewis")); System.out.println("Names for those whose ag >= 30 are: "); for(String s: hashMap.keySet()) if(hashMap.get(s) >= 30) System.out.println(s+" "+ hashMap.get(s));
  • 46. Continue-Exercise(3)_Solution // Create a TreeMap from the preceding HashMap Map<String, Integer> treeMap = new TreeMap<String, Integer>(hashMap); System.out.println("Display entries in ascending order of key"); System.out.println(treeMap); } }// end class
  • 47. 47 Exercise(4): Counting the Occurrences of Words in a String Write Java program to count the occurrences of words in a text and displays the words and their occurrences in ascending order of the words. Assume text is: "Good morning. Have a good class. " + "Have a good visit. Have fun!" The program uses a hash map to store a pair consisting of a word and its count. For each word, check whether it is already a key in the map. If not, add the key and value 1 to the map. Otherwise, increase the value for the word (key) by 1 in the map. Display the content of the Map. Run CountOccurrenceOfWords
  • 48. Solution of Exercise(4) import java.util.*; public class CountOccurrenceOfWords { public static void main(String[] args) { String text = "Good morning. Have a good class. " + "Have a good visit. Have fun!"; Map<String, Integer> map = new TreeMap<String, Integer>(); String[] words = text.split("W+"); // split text into words , this mean the delimiter will be anything that is not a word. for (int i = 0; i < words.length; i++) { String key = words[i].toLowerCase(); if (key.length() > 0) { if (!map.containsKey(key)) map.put(key, 1); else { int value = map.get(key); value++; map.put(key, value); } } } //for
  • 49. Continue Solution of Exercise(4) System.out.println(“Words t Count”); System.out.println(“----------------------------”); for(String t : map.keySet()) System.out.println(t+”t“+ map.get(t)); }//main }//class
  • 50. Important Notes  The Collection Framework has two rooted interfaces: Collection, and Map.  Set, List, and Queue are sub-Interfaces from Collection Interface.  Distinguish between Collection Interface, and the Collections class that is used to do some operations on the ArrayList such as: reverse, sort, etc as you studied in Meeting6.  You did not use Collection Interface methods directly, you use its sub-Interfaces to declare objects of Set, List, or Queue then use objects to onvoke methods. Wherein Collections class methods are used using Collections class to invoke methods: Collections.sort(x), etc.
  • 51. Please solve the Activity of Meeting 8.