loadCountries(String[] countries){
ArrayList Java Collections Java Collections Collections in Java LEVEL PRACTITIONER Ashok Kumar Kanuparthi(g-Ashok3)/Renjith(t-renjith)/ Shanmu (105110) Trainer/Trainer/ Sr Architect 1.0, January 1st 2012 Icons Used Questions Tools Coding Standard s Case Study Demonstrati on Worksho p Objectives Collection Collections Framework Easy to maintain Easy to use. Example: The collection sizes dynamically changes that is it gets shrunk or increased based on the elements stored. Collection Interfaces A SortedMap is a Map that maintains its entries in ascending order, sorted based on the key Problem 1 : You need to insert the above list of countries in the same order given above . What type of collection can be used ? Solution : Any ordered collection can be used. Example: List. Problem 2: Suppose you want to automatically sort the country names and store it in a collection ? What type of collection can be used ? Solution : A sorted collection like SortedSet can be used which automatically sorts and rearranges the value each time a new country is added to the list. List Vector Array List Hash Set Tree Set Vectors can hold duplicate values. This is thread safe. Array List can hold duplicate values. This is not thread safe. Can hold null values. 10 It allows duplicates Set: 11 Time To Reflect Associates to reflect the following before proceeding. What is the collection type that can be used to hold duplicate values? What type of collection can be used for thread safe storage of elements with duplication? What type of collection can be used to store unique elements in a sorted order? 12 Collection Interface 13 List Interface List implementations: Array List 16 17 18 Consider the code below what happens if the ArrayList API becomes deprecated ? How many changes should be done in the below code ? All the red boxes are changes to be done. Lets see how to reduce it. 19 The solution is declaring the reference variable as the interface type rather than of the implementation type. Example all the list objects can be declared using List type. Now change needs to be done in one place, where the object is created. 20 Adds the element lemon at position 1 moving orange to position 2. Adds elements one by one to the list. When set is used the item in the particular index will be replaced by the new item. 21 22 Create a class named ArrayListEx and develop the method as mentioned below and from the main method trigger this method and check the output. Creates an array list object and adds the country names to it. 23 Add the following method in the ArrayListEx class and from the main method trigger this method and check the output. Note: When a primitive is added to a collection it gets automatically converted to its equivalent wrapper object and loaded in the list. 24 Add the following method in the ArrayListEx class and from the main method trigger this method and check the output. The list returned by the previous problem statement should be passed as and input to this method. 25 Output 26 Set Interface 27 HashSet 28 29 http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html 30 Elements can be added one by one using a add() method or an entire collection can be added using the addAll() method. Example: mySet.add(India); Note : If an entire set is added to another set , the duplicate elements will not get added. 31 32 Create a class SetEx, add the below method to the class. Invoke the method from a main method and test the method. Always remember to declare the collection using the appropriate interface. In the example it is Set. 33 Add the below method to the SetEx class. Invoke the method from a main method and test the method. Note: When a primitive is added to a collection it gets automatically converted to its equivalent wrapper object and loaded in the list. 34 Add the below method to the SetEx class. Invoke the method from a main method and test the method. 35 Output 36 Time To Reflect Associates to reflect the following before proceeding. What method can be used to merge to two array lists ? What happens when a duplicate entry is tried to be added to a set ? What is the difference between add and set method in arraylist? How to add an element to a particular position in an array list? 37 38 Roses Jewels Chocolate Here, the buyer is aware of what is inside the boxes ,since the box is labeled. This makes his job easier since he knows what he can put in and what he can take out from the box 39 Similar to the boxes how can one know what is the data type of the element stored in a collection? 40 What is Generics? Generics is a feature allows the programmer to specify the data type to be stored in a collection or a class when developing the program. Compile throws error if the data stored is different from the data type specified in the generic. 41 We will take the same box example but instead of jewels , chocolates and roses we will store java objects inside it. Consider a Box class, 42 43 44 We can declare collection to hold a specific data type elements using generics . Syntax: InterfaceName <Type> varName=new Implementation<Type>(); Example : Declares an array list for holding only integer values. List<Integer> myList=new ArrayList<Integer>(); 45 1. Avoid unnecessary type casting : Using generics avoid the need of typecasting while retrieving the elements from the collection. Consider an ArrayList named countries ,elements can be retrieved from the List as shown below Without Generics With Generics 46 2. Minimize CastException during run time: For example assume a method returns a List of integers. The client is unaware about the type of data held by the collection and he may type cast it to some incompatible type and end up in CastException during runtime. In case of any invalid casting compiler will throw an error.. 3. Easy Maintenance & Readability : Looking at the code the developer can easily know the data type stored in the collection and thus helps him to process the collection easily. 47 48 Create a class named GenericEx and add the method given below. Generic Declaration Try to add a Integer number to the List and see how the program behaves. 49 Generic Declaration 50 Output 51 Let us now see how to iterate through the collection and read elements one by one. The following are the ways to iterate through a collection For-each loop Iterator ListIterator 52 We will go through each of the iteration mechanism using a lend a hand example. We will reuse the classes we developed as part of the previous lend a hand, 1. ArrayListEx 2. SetEx 53 54 Create a class named ForLoopExMain with a main method. Add the following lines of code inside main method which can read the Country list from ArrayListEx and print it. Note : Since Generics is not used, we can see that elements are explicitly casted to String type. 55 Add the following lines of code inside the main method to read the number list from ArrayListEx and calculate the sum of all the numbers in the list. 56 For-Each loop 57 58 59 Create a class named ForEachExMain with a main method Add the following lines of code to read the countries set from the SetEx class and iterate using for each loop and print it. 60 Add the following lines of code to the main method to find the sum of numbers in the number set read from the SetEx class 61 62 Iterator Iterator interface methods: Method boolean hasNext() Object next() void remove() Description true if there are more elements for the iterator. Returns the next object or elements. Removes the element that was returned by next from the collection. This method can be invoked only once per call to next . 63 64 It.next( ) It.next( ) It.next( ) The next element is retrieved everytime it.next() is executed. The hasnext() method is used for verifying the existence of element in the collection before firing the next(). 65 66 67 Create an iterator to work on the set Invoke the hasNext() method to check whether the iterator contains elements to be read. Invoke the next() method to read each country from the Set. Note :The Iterator is also declared with generics to avoid type casting. 68 69 ListIterator An list iterator can be used by programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). Note : In projects Iterator interface are used commonly. So we are not going to learn the implementation of ListIterator. Associates can refer to the oracle documentation for more details on ListIterator. 70 Time To Reflect Associates to reflect the following before proceeding. How to make a collection accept only Integer objects? What are all the methods available to iterate through a Set? Can a ListIterator be used with a Set? Which iterator can be used to add elements to a list in between the iteration process? What may be the reason that for loop is not used to iterate through set? Maps 72 Map Interfaces Hash Map Hash Table Tree Map 73 Collection Map L Bi In the case of collection we can see that the search traverses across the entire collection to get the required object. But in the case of map it is directly accessed using the key. 74 Map Interface 75 Description Returns a set with all the keys contained in this map. Associates the specified value with the specified key in this map. void putAll(Map t) Copies all of the mappings from the specified map to this map Object remove(Object key) Removes the mapping for this key from this map if it is present int size() Returns the number of key-value mappings in this map. Collection values() Returns a collection with all the values contained in this map. 76 HashMap 77 Syntax: Map<Type1,Type2> mapName=new HashMap<Type1,Type2>(); Creates a map with generics defined key of the type Type1 and value of the type Type2. Example: Creates map object supporting Integer key and String value. Map<Integer,String> myMap=new HashMap<Integer,String>(); Always remember to declare the Map using the appropriate interface. In the example it is Map. 78 Adding Elements to a Map: Elements can be added to a map as key - value pairs using the put() method Syntax : map.put(key,value); Example: map.put(1,India); // This adds an country India with a key value 1. Reading Elements From a Map: Elements can be retrieved from a map by passing the key using the get() method. Syntax : variable =map.get(key); Example: String country=map.get(1); // This retrieves the country specific to key 1 which is India. 79 keySet() method 80 81 Create a class named MapEx. It should loads a map with student registration number as key and student name as value and returns the student map. Always remember to declare the Map using the appropriate interface. In the example it is Map. 82 Let us now iterate through the map and print the name and the registration number. Prints the map Gets the key Set for the map Gets the iterator for the keyset Iterates over the key set and reads the value for each key. 83 What can be done to automatically sort the map according to the registration number ? The solution is TreeMap, since Tree implements the SortedMap interface, it automatically stores the elements in a sorted order based on the key. 84 Note : See how easily we changed the implementation from HashMap to TreeMap by making just one change. This is the advantage of declaring collections with the interface Map. 85 Notice the output the student records are displayed based on the registration number order. 86 Time To Reflect Associates to reflect the following before proceeding. What types of map can be used to if want to allow null values? Suppose you are asked to create a telephone directory with person's name in a sorted order which map implementation do you prefer to use ? 87 User defined classes can be stored in any of the collections like list , set map etc. In the next lend a hand we will see how user defined objects can be added and retrieved from an ArrayList. Same procedure applies for all other collections. NOTE: To add a user defined object to a sorted collection developers should either Make the User Defined object to implement Comparable interface (or) Create a custom comparator class and pass it as constructor parameter when creating the collection object. Refer the following links for more details : http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html http://docs.oracle.com/javase/1.3/docs/api/java/util/Comparator.html 88 Consider a scenario in which you want to send the details of students to a method. The student details includes roll number , name , address, phone number and email id. Suppose there are 50 students what can be done to pass the details of all the 50 students together ? Let us see how to solve it? Step 1 : Create a Student class with the roll number, name , address as its fields. Step 2 : Create an object of Student class for each student and load the details. Step 3 : Create an ArrayList and add each of the Student objects to the list. Step 4 : Pass the list as argument to the method. 89 Let us create a StudentManager class with method printStudentDetails() accepts the student details as a list of student objects. Components to be developed: 1. Student Class : For holding the student details. 2. StudentManager class : Contains method for printing the student details. 3. MainClass class : Creates 5 student objects , adds them to a list and pass it to the printStudentDetails() method of the StudentManager class. 90 The Student class should have the following fields to hold the student details 1. roll number 2. name 3. address 4. phone number 5. email id All the fields should be created as private and accessed using public methods. 91 All the methods starting with the word get are used to read the associated field value. Example : getName() returns the name. The values to the member variables can be initialized using the overloaded constructor. 92 Creates ArrayList objects and adds the student objects to the list. Passes the list as input to printStudentDetails method 93 94 Core JavaUploaded by
Ajay Singh PhogatUploaded by
Ajay Singh PhogatCore Java
About the Author
Created By: Credential Information: Version and Date:
ognizant Certified Official Curriculum
Hands on ExerciseTest Your Understan ding
3Best Practices & Industry Standards
After completing this session, you will be able to : Define Collections Describe usage of collections Describe the benefits of collections Understand the core Collection Interfaces Understand the implementationsWhat are Collections?
What is a collection? A collection is a container that groups multiple elements into a single unit.
Elements 1nIn java world, a collection represents a group of objects, known as elements.
What is a collections framework? A collections framework is a unified architecture for representing and manipulating varieties of collections. Some collections allow duplicate elements and others do not. Can be used only to hold object type data (non primitive type). Some are ordered and others are unordered. The collection framework is available in the java.util package. Collection framework contains, A set of Interfaces. Concrete class implementations for the interfaces. The classes in turn has standard APIs for processing collections.
6Benefits of Collection framework
Example: This provides methods for sorting which need not be developed, from scratch thus reducing the development effort.Reduces Programm ing Effort
Collection Framework Benefits
High performan ce APIs
Example: The APIs provided are proven tested ones with high performance.The APIs are easy to use and maintain.
Resizable & grows
What are collection Interfaces? These are set of predefined java interfaces defined in java.util package which can be used for performing any logic related to collection of Objects. Example: Set, List, Map What are collection Implementations? These are predefined classed which implements one of the collection interfaces. The programmer uses these for processing collection of Objects. Example: ArrayList, HashMap.Sorted Vs Ordered Collection
Consider you have a collection country names.
1. India 2. Australia 3. England 4. New Zealand 5. South AfricaCollection Framework Components
Collection The root interface in the collection hierarchy. Set This is an interface. A collection that cannot contain duplicate elements. This is an interface. An ordered collection which contain duplicate elements.
Allows null. Does not allow duplicate values.
Allows entries to be sorted in a specific order.
Difference between Set and List
List :
Cat Dog Bat Bat Lion Cat Lion Bird null nullIt permits multiple null values.
Cat Dog Bat Lion Bird nullIt does not allow duplicates
Only one null value is permitted
The root interface in the collection hierarchy. JDK does not provide any direct implementations of this interface, it provides implementations of more specific sub-interfaces like Set and List etc. Contains methods which needs to implemented directly or indirectly by the sub classes. For more details on the methods specified in Collection interface refer, http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
Used for storing the elements in a ordered way. Supports duplicate entries. Supports index based additions and retrieval of items. 1. Vector 2. ArrayList 3. LinkedList We will be covering only ArrayList implementation in details. For details on the other List Implementations refer LinkedList- http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html. Vector - http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html. 14
Implements List interface ArrayList can grow and shrink in size dynamically based on the elements stored hence can be considered as a variable array. Values are stored internally as an array hence random insert and retrieval of elements are allowed. Can be traversed using a foreach loop, iterators, or indexes. Initially gets created with an initial capacity , when this gets filled the list automatically grows. Can hold only object type data Cannot hold primitive type values. Supports duplicate entries. 15Important ArrayList methods
Method void add(int index, Object element) boolean add(Object o) boolean addAll(Collection) Description Inserts the specified element at the specified position in this list. Appends the specified element to the end of this list. Appends all of the elements in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. boolean addAll(int index, Collection c) Inserts all of the elements in the specified Collection into this list, starting at the specified position. void clear() boolean contains(Object elem) Object get(int index) Removes all of the elements from this list. Returns true if this list contains the specified element. Returns the element at the specified position in this list.Important ArrayList methods
Method int indexOf(Object elem) Description Searches for the first occurrence of the given argument, testing for equality using the equals method. int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this list. Object remove(int index) void removeRange(int fromIndex, int toIndex) Object set(int index, Object element) int size() Object[] toArray() Removes the element at the specified position in this list. Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. Replaces the element at the specified position in this list with the specified element. Returns the number of elements in this list. Returns an array containing all of the elements in this list in the correct order. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.htmlHow to Create an Array List ?
ArrayList can be created by using any of the three possible constructors given below 1. ArrayList() : Constructs an empty list. 2. ArrayList(Collection c) : Constructs a list from an existing collection, containing the elements of the specified collection. 3. ArrayList(int initialCapacity) : Constructs an empty list with the specified initial capacity. Syntax : List listName=new ArrayList(); Example : List mylist=new ArrayList();Why ArrayList object is declared as the interface type List?
Need for declaring using interface type?
Need for declaring using interface type? (Cont)
How to add elements in a ArrayList?
Values can be added to an ArrayList using any of the add methods. Syntax : listName.add(element); Example : Create an arraylist List myList=new ArrayList() myList.add(Apple); myList.add(Orange); myList.add(1,lemon ); myList.set(0,banan a); 0 1 2
Orange OrangeApple banana Orange Lemon Lemon
Lend a Hand - ArrayList
Objective: In this lend a hand we are going to learn about creating and adding elements into the array list. Problem Statement 1: Create a method that accepts the names of five countries and loads them to an array list and returns the list. Problem Statement 2 : Create an method which can return an array list holding values 1-10. Problem Statement 3 : Create a method needs to return an array list holding value 1-15. The method should make use of the already created array list containing values up to 10 and then add values from 11-15 using a for loop.Lend a Hand Solution Problem Statement 1
Always remember to declare the list using List interface.
Lend a Hand Solution Problem Statement 2
Lend a Hand Solution Problem Statement 3
addAll () method adds the entire list to the new list
Lend a Hand Solution Run the program
Create a Main Class and execute the methods.
The Set interface is a collection that cannot contain duplicate elements. It permits a single element to be null. Set interface contains methods inherited from collection interface. Sorted Set interface is a set that maintains its elements in ascending order. Set Implementations: 1.HashSet 2.TreeSet
We will be covering only HashSet in detail in this session. For details on TreeSet visit http://docs.oracle.com/javase/1.4.2/docs/api/java/util/TreeSet.html
Implements the Set interface hence doesnt support duplicate entries. Does not support random access or retrieval. Cannot predict the order in which the items get stored in the Set. Not Thread safe. Permits Null value(Only one).How to create an HashSet ?
HashSet can be created by using the following syntax Set setName=new HashSet(); Example : Set countries=new HashSet();Important Methods in HashSet
Method boolean add(Object element) Description Adds the specified element to this set if it is not already present. void clear() boolean contains(Object o) boolean isEmpty() Iterator<E> iterator() boolean remove(Object o) int size() Removes all of the elements from this set. Returns true if this set contains the specified element. Returns true if this set contains no elements. Returns an iterator over the elements in this set. Removes the specified element from this set if it is present. Returns the number of elements in this set.How to add elements to HashSet?
Adds two elements into the set.mySet.add(Australia); mySet.add(India) mySet.addAll(mySet1);
Returns false since India already exists in the set. Adds all the items of Set mySet1 to mySetLend a Hand - HashSet
Objective: Let us learn how to create a HashSet and add elements into it. Problem Statement 1: Create a method that accepts the names of five countries and loads them to an HashSet and returns the Set. Problem Statement 2 : Create an method which can return a set holding values 1-10. Problem Statement 3 : Create a method needs to return a set holding value 115. The method should make use of the already created set containing values up to 10 and then add values from 11-15 using a for loop.Lend a Hand Solution Problem Statement 1
Lend a Hand Solution Problem Statement 2
Lend a Hand Solution Problem Statement 3
Lend a Hand Solution Main Class
Create a main class as given below and execute it.Let us now learn about Generics
Real World Example
Let us take a real time example
The buyer does not know what these red shape boxes contain. Hence the buyer needs to open these boxes every time to find what is inside itHow to identify data type in a collection?
Generics is the solution.
Lets Analyze Generics Programmatically.
public class Box { private Integer width; public void addWidth(Integer width) { this.width = width; } public Integer getWidth() { return width; } } Assume that I have to pass width as a Float (or) Double to the Box class. How can I achieve this? Generics is the solution.Generics solves the problem.
We will modify the Box class with generics as shown below. public class Box<Type> { // T stands for "Type private Type width; public void addWidth(Type width) { this.width = width; } public Type getWidth() { return width; } } As shown in the example Type refers to the data type of the width field which is declared as generic argument of the class. Instead of declaring width as Integer we have declared as a generic data type Type. When declaring Box object, we can pass any data type for Type which affects all the Type declarations inside the class. Example: Box<Float> will declare a box object whose width field data type is Float An object can created as Box<Float> box=new Box<Float>(); By doing this we can ensure the same Box behaving differently for different data type.Generics usage in Collections
Collections declared with generic (data type) ensures that the collections hold only elements of particular data type. Java collections have been defined with generics for it accept objects of any data type. Example: Java ArrayList class is defined with a generic as shown below depicting that the collection can accept generics with any data type.Using Generics With Collection
Advantages of using Generics with Collection
Type Casted to String
No need of type casting
Advantages of using Generics with Collection
Lend a Hand- Generics
Objective: Let us learn how to declare/process collections declared with generics. Problem Statement 1 : Create a method which can accept a collection of country names and add it to ArrayList with generic defined as String and return the List. Problem Statement 2 : Create a method which can create a HashSet containing values 1-10. The Set should be declared with the generic type Integer. The method should return the Set.Lend a Hand Solution Problem Statement 1
Lend a Hand Solution Problem Statement 2
Add the below method to GenericEx class.
Lend a Hand Main Class
Create a class named GenericExMain with a main methodHow to Iterate Through Collection Elements ?
For loop Reads elements by specifying the index using the get() method Can be used only with List. Iterate over a list and gets the elements one by one until the complete list is covered Can be applied with both List and Set. Iterator provides methods to iterate through a collection. Can be applied with both List and Set. An iterator which support both forward and back ward iteration. Can be applied only with List.Lend a Hand Iterating Collection
Lend a Hand :For Loop
Objective: We will learn how to the iterate through the List objects using a for loop. Create a class with a main method which reads the lists from the ArrayListEx and iterates through the list. Problem Statement 1 : The main method should read the country list and read it one by one , store in a String object and print the country names in separate lines. Problem Statement 2: The main method should retrieve the list of numbers from 1-10 using the get1To10 method in ArrayListEx class and find the sum of numbers in the list and print the sum.Lend a Hand Problem Statement 1
Reads the size of the list
The for loop iterates from 0 to size-1 and reads elements one by one.Lend a Hand Solution Problem Statement 2
1. For each loop was added as a part of java 5 2. Can be used to read elements from a collection or array 3. The advantage of for each is that we dont need to specify the index. It automatically iterates over the specified object and reads values one by one. Syntax :
for(datatype variableName : collectionName){ loop body } Example for(Object a : myList){ } Reads elements as objects one by one from the list MyList and System.out.println(a); assign to the variable a. Reads each element of the collection collectionName with the type datatype and assigns it to the variable variableName one by one.Lend a Hand for Each loop
Objective: We will learn how to use for each loop for iterating through Sets. We will use the Set created in SetEx class which we developed in our previous lend a hand. Create a class named ForEachExMain with a main method which iterates through the Set. Problem Statement 1 : The main method should read the set of countries returned by getCountries() method in SetEx class and print the names of countries in separate lines. Problem Statement 2 : The main method also should calculate the sum of numbers in the set returned by the get1To10() method in the SetEx class. Prerequisite: Declare the Sets with respective generic types. The getCountries() method should return a Set with String generic type and get1To10() method should return an Set with generic type Integer.Lend a Hand :For Each loop
Adding generics to the collections of getCountries() and get1To10() methods.Lend a Hand Solution Problem Statement 1
Lend a Hand Problem Statement 2
Lend a Hand Execute the main class
Run the class ForEachExMain
What is an Iterator interface? This interface contains methods which is used for iterating & accessing all the elements of a collection in sequence. The List and Set collections can be iterated using iterators.How to Create an Iterator?
An Iterator is created for a particular collection object by calling the iterator() method on the collection object. Syntax : Iterator<type> iteratorName=collection.iterator(); Where type is the generic type of the Iterator Example : Creates an iterator to iterate the elements of the myList containing Integer objects. Iterator<Integer> myListIterator = myList.iterator();How an iterator works?
Working of Iterator
it.hasNext() it.hasNext() it.hasNext() it.hasNext()
No element, hence loop terminatedIterator<Integer> it=myList.iterator(); Iterator Object created
Steps for using Iterator
Step 1 : Create Iterator object Iterator<Integer> iterator=myList.iterator(); Step 2 : Check whether next element exist using the hasNext() method
while(iterator.hasNext()) { // Read Elements } Step 3 : Read the element using the next() method. while(iterator.hasNext()) { int number=iterator.next(); }Lend a Hand Iterator
Objective: We will learn how to use an Iterator to iterate through a Set. We will use the SetEx class developed in the previous lend a hand for this demo. The Sets in the SetEx class is expected to be declared using generics.. Problem Statement : Iterate through the countries (Set) returned by the getCountries() method of the SetEx class and print the country names one by one.Lend a Hand Iterator Solution.
Create a class named IteratorExMain as shown below.Lend a Hand Execute the main method
Run the class named IteratorExMain
71
Map stores Elements as key value pairs. Each key maps to one value stored in the map. The values can be accessed by passing the key. The key should be unique used to identify the value. The key and value can only be objects.
Key 1 2 3 4 5 Value India Australia England South Africa New Zealand
Map A Map is an object that maps keys to valuesCan contain null values. Not Thread Safe
Key C D B A E Value Cat Dog Null Null BirdCannot contain null values. This is Thread Safe
Key C D B A E Value Cat Dog pigeon cow BirdStores in sorted order according to the key Not Thread safe.
Key A B C D E Value Null Null Cat Dog BirdDifference between Collection interfaces and Map
Cat Dog Bat Lion Bird Key C D B
Value Cat Dog Bat Lion BirdHow Lion look up happens?
Map interface is the root interface in the map hierarchy All map implementations should implement this interface directly or indirectly. Important Methods:
Methods Description void clear() Removes all mappings from this map (optional operation). boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key. boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value. Set entrySet() Returns a set view of the mappings contained in this map. Object get(Objectkey) Returns the value to which this map maps the specified key.boolean isEmpty() Returns true if this map contains no key-value mappings.
Map Interface Important Methods(Cont)
Method Set keySet() Object put(Object key, Objectvalue)
Implementation of the Map interface. Permits null values for key(only one key) and value. Not Thread safe. Does not maintain the order of elements in the Map.How to Create a HashMap Object?
How to add and retrieve elements in a HashMap?
keySet() returns the set of keys for the map Using the keys obtained one can iterate the map. Set<Integer> keys=map.keySet(); Iterator<Integer> iterator=keys.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }
Get the iterator of the Set. Iterating the set and printing the key values. Get the keys of the Map.Lend a Hand - HashMap
Objective: Let us learn to store values in a map, iterate through the map and print the values. Problem Statement 1: Create a method that returns a Hash map containing the details of students. Roll no is the key and student name is the value. Problem Statement 2 : Create a main method that reads the student map and prints the roll number and name of all the students by iterating through the keys.Lend a Hand Solution Problem Statement 1
Lend a Hand Solution Problem Statement 2
Lend a Hand - Output
Lend a Hand TreeMap Demo
In this lend a hand we will see how TreeMap can be used to store elements sorted by the key. We will tweak the previous program to use TreeMap rather than HashMap implementation. Solution: Change the HashMap to TreeMap in the getStudentDetails() method in MapEx class. Map<String,String> studentMap=new HashMap<String, String>();Map<String,String> studentMap=new TreeMap<String, String>();
Lend a Hand TreeMap Output
How to store user defined objects in collections?
Lend a Hand Adding user defined object in collection
Lend a Hand Adding user defined object in collection
Lend a Hand : Create Student class
Lend a Hand : Student class Code
Lend a Hand : Main Class Code
Creates five Student objects
Lend a Hand : Create StudentManager class Code
The printStudentDetails() method accepts list of students as argument.
You have successfully completed Collections in Java
You might also like