SlideShare a Scribd company logo
1 of 24
Core Java Training
Collections - Maps
Page 1Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 1
Agenda
• Collections – Maps
• Map Interface
• Map methods
• Mapuse
• Hashmap
• Treemap
• Utilities
Page 2Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 2
Map Interface Context
Map
Page 3Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 3
Map Interface
• Stores key/value pairs
• Maps from the key to the value
• Keys are unique
• a single key only appears once in the Map
• a key can map to only one value
• Values do not have to be unique
Page 4Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 4
Map methods
Page 5Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 5
Map views
• A means of iterating over the keys and values in a Map
• Set keySet()
• returns the Set of keys contained in the Map
• Collection values()
• returns the Collection of values contained in the Map. This Collection
is not a Set, as multiple keys can map to the same value.
• Set entrySet()
• returns the Set of key-value pairs contained in the Map. The Map
interface provides a small nested interface called Map.Entry that is
the type of the elements in this Set.
Page 6Classification: Restricted
Map.Entry interface Example
import java.util.*;
class MapInterfaceExample{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Page 7Classification: Restricted
Exercise..
• Create a Map with 5 values…
• Iterate through and print
• the keys,
• the values,
• both the keys and the values of the Map
Page 8Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 8
HashMap and TreeMap Context
HashMap TreeMap
Map
Page 9Classification: Restricted
HashMap and TreeMap
• HashMap
• The keys are a set - unique, unordered
• Fast
• TreeMap
• The keys are a set - unique, ordered
• Same options for ordering as a TreeSet
• Natural order (Comparable, compareTo(Object))
• Special order (Comparator, compare(Object, Object))
Page 10Classification: Restricted
HashMap
• A HashMap contains values based on the key.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
Page 11Classification: Restricted
HashMap Constructors
Page 12Classification: Restricted
HashMap methods
Page 13Classification: Restricted
HashMap Example: remove()
import java.util.*;
public class HashMapExample {
public static void main(String args[]) {
// create and populate hash map
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(101,"Let us C");
map.put(102, "Operating System");
map.put(103, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Page 14Classification: Restricted
Difference between HashSet and HashMap
• Think…
Page 15Classification: Restricted
HashMap Example: Book
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author,
String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class MapExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new HashMap<Integer,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(1,b1);
map.put(2,b2);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+
"+b.quantity);
}
}
}
Page 16Classification: Restricted
Exercise..
• What is a TreeMap? Implement the book example for TreeMap.
• What is a LinkedHashMap?
• What is a HashTable? How is it different from a HashMap?
• What is Comparable and Comparator interfaces in Java? How are they
different? Write programs utilizing both to test their usage.
Page 17Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 17
Bulk Operations
• In addition to the basic operations, a Collection may provide “bulk” operations
boolean containsAll(Collection c);
boolean addAll(Collection c); // Optional
boolean removeAll(Collection c); // Optional
boolean retainAll(Collection c); // Optional
void clear(); // Optional
Object[] toArray();
Object[] toArray(Object a[]);
A = {1,2,3,4} B={2,3,4,5}
addAll() -> A U B = {1,2,3,4,5} UNION
A = STUDENTS LEARNING JAVA; B = STUDENTS LEARNING .NET
A U B = ALL STUDENTS LEARNING EITHER JAVA OR .NET OR BOTH
A INTERSECTION B = ALL STUDENTS LEARNING BOTH JAVA AND .NET
removeAll() -> A-B = {1}, B-A={5}..
A IS ALL EMPLOYEES, B IS EMPLOYEES SERVING NOTICE PERIOD
A-B = EMPLOYEES NOT SERVING NOTICE PERIOD
retainAll() -> A INTERSECTION B = {2,3,4}
Page 18Classification: Restricted
HashMap vs TreeMap
• HashMap can contain one null key. TreeMap cannot contain a null key.
• HashMap does not maintain any order, whereas TreeMap maintains
ascending order.
Page 19Classification: Restricted
Utilities Context
Page 20Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 20
Utilities
• The Collections class provides a number of static methods for fundamental
algorithms
• Most operate on Lists, some on all Collections
• Sort, Search, Shuffle
• Reverse, fill, copy
• Min, max
• Wrappers
• synchronized Collections, Lists, Sets, etc
• unmodifiable Collections, Lists, Sets, etc
Page 21Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 21
Properties class
• Located in java.util package
• Special case of Hashtable
• Keys and values are Strings
• Tables can be saved to/loaded from file
Page 22Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 22
Topics to be covered in next session
• Inner Classes
• Method-local Inner Class
• Anonymous Inner Class
• Static Nested Inner Class
Page 23Classification: Restricted
3-February-
2003
cse403-10-Collections © 2003 University of Washington 23
Thank you!

More Related Content

What's hot

Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

What's hot (20)

Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java collection
Java collectionJava collection
Java collection
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Generics
GenericsGenerics
Generics
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
L11 array list
L11 array listL11 array list
L11 array list
 
Applets
AppletsApplets
Applets
 
Exception handling
Exception handlingException handling
Exception handling
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Java exception
Java exception Java exception
Java exception
 

Similar to Collections - Maps

CON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptx
CON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptxCON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptx
CON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptx
skypy045
 

Similar to Collections - Maps (20)

Session 20 - Collections - Maps
Session 20 - Collections - MapsSession 20 - Collections - Maps
Session 20 - Collections - Maps
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array List
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collections
CollectionsCollections
Collections
 
Collections
CollectionsCollections
Collections
 
Collectionsand GenericsInJavaProgramming.ppt
Collectionsand GenericsInJavaProgramming.pptCollectionsand GenericsInJavaProgramming.ppt
Collectionsand GenericsInJavaProgramming.ppt
 
Session 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsSession 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, Sets
 
collections
collectionscollections
collections
 
Best core & advanced java classes in mumbai
Best core & advanced java classes in mumbaiBest core & advanced java classes in mumbai
Best core & advanced java classes in mumbai
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.ppt
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
CON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptx
CON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptxCON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptx
CON5423-GS-Collections-and-Java-8-Functional-Fluent-Friendly-and-Fun.pptx
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
22.ppt
22.ppt22.ppt
22.ppt
 
adjava_23_bcs_vision_academy_sachinsir.pdf
adjava_23_bcs_vision_academy_sachinsir.pdfadjava_23_bcs_vision_academy_sachinsir.pdf
adjava_23_bcs_vision_academy_sachinsir.pdf
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
 

More from Hitesh-Java

More from Hitesh-Java (20)

Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
JDBC
JDBCJDBC
JDBC
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
 
Review Session - Part -2
Review Session - Part -2Review Session - Part -2
Review Session - Part -2
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 
Object Class
Object Class Object Class
Object Class
 
Exception Handling - Continued
Exception Handling - Continued Exception Handling - Continued
Exception Handling - Continued
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Collections - Maps

  • 2. Page 1Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 1 Agenda • Collections – Maps • Map Interface • Map methods • Mapuse • Hashmap • Treemap • Utilities
  • 3. Page 2Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 2 Map Interface Context Map
  • 4. Page 3Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 3 Map Interface • Stores key/value pairs • Maps from the key to the value • Keys are unique • a single key only appears once in the Map • a key can map to only one value • Values do not have to be unique
  • 5. Page 4Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 4 Map methods
  • 6. Page 5Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 5 Map views • A means of iterating over the keys and values in a Map • Set keySet() • returns the Set of keys contained in the Map • Collection values() • returns the Collection of values contained in the Map. This Collection is not a Set, as multiple keys can map to the same value. • Set entrySet() • returns the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set.
  • 7. Page 6Classification: Restricted Map.Entry interface Example import java.util.*; class MapInterfaceExample{ public static void main(String args[]){ Map<Integer,String> map=new HashMap<Integer,String>(); map.put(100,"Amit"); map.put(101,"Vijay"); map.put(102,"Rahul"); for(Map.Entry m:map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }
  • 8. Page 7Classification: Restricted Exercise.. • Create a Map with 5 values… • Iterate through and print • the keys, • the values, • both the keys and the values of the Map
  • 9. Page 8Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 8 HashMap and TreeMap Context HashMap TreeMap Map
  • 10. Page 9Classification: Restricted HashMap and TreeMap • HashMap • The keys are a set - unique, unordered • Fast • TreeMap • The keys are a set - unique, ordered • Same options for ordering as a TreeSet • Natural order (Comparable, compareTo(Object)) • Special order (Comparator, compare(Object, Object))
  • 11. Page 10Classification: Restricted HashMap • A HashMap contains values based on the key. • It contains only unique elements. • It may have one null key and multiple null values. • It maintains no order.
  • 14. Page 13Classification: Restricted HashMap Example: remove() import java.util.*; public class HashMapExample { public static void main(String args[]) { // create and populate hash map HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(101,"Let us C"); map.put(102, "Operating System"); map.put(103, "Data Communication and Networking"); System.out.println("Values before remove: "+ map); // Remove value for key 102 map.remove(102); System.out.println("Values after remove: "+ map); } }
  • 15. Page 14Classification: Restricted Difference between HashSet and HashMap • Think…
  • 16. Page 15Classification: Restricted HashMap Example: Book import java.util.*; class Book { int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } public class MapExample { public static void main(String[] args) { //Creating map of Books Map<Integer,Book> map=new HashMap<Integer,Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to map map.put(1,b1); map.put(2,b2); map.put(3,b3); //Traversing map for(Map.Entry<Integer, Book> entry:map.entrySet()){ int key=entry.getKey(); Book b=entry.getValue(); System.out.println(key+" Details:"); System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+ "+b.quantity); } } }
  • 17. Page 16Classification: Restricted Exercise.. • What is a TreeMap? Implement the book example for TreeMap. • What is a LinkedHashMap? • What is a HashTable? How is it different from a HashMap? • What is Comparable and Comparator interfaces in Java? How are they different? Write programs utilizing both to test their usage.
  • 18. Page 17Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 17 Bulk Operations • In addition to the basic operations, a Collection may provide “bulk” operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional Object[] toArray(); Object[] toArray(Object a[]); A = {1,2,3,4} B={2,3,4,5} addAll() -> A U B = {1,2,3,4,5} UNION A = STUDENTS LEARNING JAVA; B = STUDENTS LEARNING .NET A U B = ALL STUDENTS LEARNING EITHER JAVA OR .NET OR BOTH A INTERSECTION B = ALL STUDENTS LEARNING BOTH JAVA AND .NET removeAll() -> A-B = {1}, B-A={5}.. A IS ALL EMPLOYEES, B IS EMPLOYEES SERVING NOTICE PERIOD A-B = EMPLOYEES NOT SERVING NOTICE PERIOD retainAll() -> A INTERSECTION B = {2,3,4}
  • 19. Page 18Classification: Restricted HashMap vs TreeMap • HashMap can contain one null key. TreeMap cannot contain a null key. • HashMap does not maintain any order, whereas TreeMap maintains ascending order.
  • 21. Page 20Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 20 Utilities • The Collections class provides a number of static methods for fundamental algorithms • Most operate on Lists, some on all Collections • Sort, Search, Shuffle • Reverse, fill, copy • Min, max • Wrappers • synchronized Collections, Lists, Sets, etc • unmodifiable Collections, Lists, Sets, etc
  • 22. Page 21Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 21 Properties class • Located in java.util package • Special case of Hashtable • Keys and values are Strings • Tables can be saved to/loaded from file
  • 23. Page 22Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 22 Topics to be covered in next session • Inner Classes • Method-local Inner Class • Anonymous Inner Class • Static Nested Inner Class
  • 24. Page 23Classification: Restricted 3-February- 2003 cse403-10-Collections © 2003 University of Washington 23 Thank you!