MAP INTERFACE
A map contains values on the basis of key,
i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains
unique keys.
A Map is useful if you have to search,
update or delete elements on the basis of
a key.
Hierarchy of map
There are two interfaces for implementing
Two interfaces
• Map
• SortedMap
Three classes:
• HashMap,
• LinkedHashMap,
• TreeMap
A Map can't be traversed, so you need to convert it
into Set using keySet() or entrySet() method.
methods of Map interface
Method Description
V put(Object key, It is used to insert an entry in the map.
Object value)
void putAll(Map It is used to insert the specified map in the map
map)
boolean It removes the specified values with the
remove(Object associated specified keys from the map.
key, Object value)
void clear() It is used to reset the map
get(Object key) This method returns the object that contains the
value associated with the key.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry<K, It returns the Set view containing all the keys
V>> entrySet() and values
V replace(K key, V value) It replaces the specified value for a
specified key.
boolean replace(K key, V It replaces the old value with the new
oldValue, V newValue) value for a specified key.
V getOrDefault(Object It returns the value to which the specified
key, V defaultValue) key is mapped, or defaultValue if the map
contains no mapping for the
boolean This method returns true if some value
containsValue(Object equal to the value exists within the map,
value) else return false.
boolean This method returns true if some key
containsKey(Object key) equal to the key exists within the map,
else return false.
Map.Entry Interface:
• Entry is the subinterface of Map. So we will be
accessed it by Map.Entry name. It returns a
collection-view of the map, whose elements
are of this class. It provides methods to get
key and value.
java HashMap class
• Java HashMap class implements the map interface
by using a hash table. It inherits AbstractMap class
and implements Map interface.
• Points to remember
• Java HashMap class contains values based on the
key.
• Java HashMap class contains only unique keys.
• Java HashMap class may have one null key and
multiple null values.
• Java HashMap class is non synchronized.
• Java HashMap class maintains no order.
Methods of Map.Entry interface
Java HashMap Example
import java.util.*;
class MapExample{
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");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
• 102 Rahul
• 100 Amit
• 101 Vijay
exampl2
• import java.util.*;
• class HashMap1{
• public static void main(String args[]){
• HashMap<Integer,String> hm=new HashMap<Integer,String>();
• System.out.println("Initial list of elements: "+hm);
• hm.put(100,"Amit");
• hm.put(101,"Vijay");
• hm.put(102,"Rahul");
•
• System.out.println("After invoking put() method ");
• for(Map.Entry m:hm.entrySet()){
• System.out.println(m.getKey()+" "+m.getValue());
• }
•
• hm.putIfAbsent(103, "Gaurav");
• System.out.println("After invoking putIfAbsent() method ");
• for(Map.Entry m:hm.entrySet()){
• System.out.println(m.getKey()+" "+m.getValue());
• }
output
• Initial list of elements: {}
• After invoking put() method
• 100 Amit
• 101 Vijay
• 102 Rahul
• After invoking putIfAbsent() method
• 100 Amit
• 101 Vijay
• 102 Rahul
• 103 Gaurav
Java LinkedHashSet class
• Java LinkedHashSet class is a Hashtable and Linked list
implementation of the set interface. It inherits HashSet
class and implements Set interface.
• The important points about Java LinkedHashSet class are:
• Java LinkedHashSet class contains unique elements only
like HashSet.
• Java LinkedHashSet class provides all optional set
operation and permits null elements.
• Java LinkedHashSet class is non synchronized.
• Java LinkedHashSet class maintains insertion order.
Constructors of Java LinkedHashSet class
Constructor Description
HashSet() It is used to construct a default
HashSet.
HashSet(Collection c) It is used to initialize the hash set
by using the elements of the
collection c.
LinkedHashSet(int capacity) It is used initialize the capacity of
the linked hash set to the given
integer value capacity.
example
• import java.util.*;
• class LinkedHashSet1{
• public static void main(String args[]){
• //Creating HashSet and adding elements
• LinkedHashSet<String> set=new LinkedHashSet();
• set.add("One");
• set.add("Two");
• set.add("Three");
• set.add("Four");
• set.add("Five");
• Iterator<String> i=set.iterator();
• while(i.hasNext())
• {
• System.out.println(i.next());
• }
• }
• }
output
• One
• Two
• Three
• Four
• Five
java LinkedHashSet example ignoring duplicate
Elements
import java.util.*;
class LinkedHashSet2{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
java TreeMap class
• Java TreeMap class is a red-black tree based implementation. It
provides an efficient means of storing key-value pairs in sorted
order.
• The important points about Java TreeMap class are:
• Java TreeMap contains values based on the key. It implements
the NavigableMap interface and extends AbstractMap class.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have multiple null
values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.
Constructors of Java TreeMap class
onstructor Description
TreeMap() It is used to construct an empty
tree map that will be sorted using
the natural order of its key.
TreeMap(Comparator<? super K> It is used to construct an empty
comparator) tree-based map that will be
sorted using the comparator
comp.
TreeMap(Map<? extends K,? It is used to initialize a treemap
extends V> m) with the entries from m, which
will be sorted using the natural
order of the keys.
TreeMap(SortedMap<K,? extends It is used to initialize a treemap
V> m) with the entries from the
SortedMap sm, which will be
sorted in the same order as sm.
Methods of Java TreeMap class
Method Description
Map.Entry<K,V> ceilingEntry(K It returns the key-value pair
key) having the least key, greater than
or equal to the specified key, or
null if there is no such key.
K ceilingKey(K key) It returns the least key, greater
than the specified key or null if
there is no such key.
void clear() It removes all the key-value pairs
from a map.
Object clone() It returns a shallow copy of
TreeMap instance.
Comparator<? super It returns the comparator that
K> comparator() arranges the key in order, or null if
the map uses the natural ordering.
NavigableSet<K> It returns a reverse order NavigableSet
descendingKeySet() view of the keys contained in the map.
NavigableMap<K,V> It returns the specified key-value pairs in
descendingMap() descending order.
int size() It returns the number of key-value pairs
exists in the hashtable.
Collection values() It returns a collection view of the values
contained in the map.
Map.Entry firstEntry() It returns the key-value pair having the
least key.
Java TreeMap Example
• import java.util.*;
• class TreeMap1{
• public static void main(String args[]){
• TreeMap<Integer,String> map=new TreeMap<Integer,String>();
• map.put(100,"Amit");
• map.put(102,"Ravi");
• map.put(101,"Vijay");
• map.put(103,"Rahul");
•
• for(Map.Entry m:map.entrySet()){
• System.out.println(m.getKey()+" "+m.getValue());
• }
• }
• }
output
• Output:
• 100 Amit
• 101 Vijay
• 102 Ravi
• 103 Rahul
What is difference between HashMap and TreeMap
HashMap TreeMap
1) HashMap can contain one null TreeMap cannot contain any null
key. key.
2) HashMap maintains no order. TreeMap maintains ascending
order.
Java Comparator interface
• Java Comparator interface is used to order
the objects of a user-defined class.
• This interface is found in java.util package and
contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
• It provides multiple sorting sequences, i.e.,
you can sort the elements on the basis of any
data member, for example, rollno, name, age
or anything else.
Methods of Java Comparator Interface
Method Description
public int compare(Object obj1, Object obj2) It compares the first object with the second
object.
public boolean equals(Object obj) It is used to compare the current object with
the specified object.
public boolean equals(Object obj) It is used to compare the current object with
the specified object.
• Student.java
• class Student{
• int rollno;
• String name;
• int age;
• Student(int rollno,String name,int age){
• this.rollno=rollno;
• this.name=name;
• this.age=age;
• }
• }
• Simple.javaIn this class, we are printing the values of the object by sorting on the basis of name and age.
• import java.util.*;
• import java.io.*;
• class Simple{
• public static void main(String args[]){
•
• ArrayList<Student> al=new ArrayList<Student>();
• al.add(new Student(101,"Vijay",23));
• al.add(new Student(106,"Ajay",27));
• al.add(new Student(105,"Jai",21));
•
• System.out.println("Sorting by Name");
•
• Collections.sort(al,new NameComparator());
• for(Student st: al){
• System.out.println(st.rollno+" "+st.name+" "+st.age);
• }
•
• System.out.println("Sorting by age");
•
• Collections.sort(al,new AgeComparator());
• for(Student st: al){
• System.out.println(st.rollno+" "+st.name+" "+st.age);
• }
• }
• }
• Sorting by Name 106 Ajay 27 105 Jai 21 101 Vijay 23 Sorting by age 105 Jai 21 101 Vijay 23 106 Ajay 27
• import java.util.*;
• class AgeComparator implements Comparator<Student>{
• public int compare(Student s1,Student s2){
• if(s1.age==s2.age)
• return 0;
• else if(s1.age>s2.age)
• return 1;
• else
• return -1;
• }
• }
• Simple.javaIn this class, we are printing the values of the object by sorting on the basis of name and age.
• import java.util.*;
• import java.io.*;
• class Simple{
• public static void main(String args[]){
•
• ArrayList<Student> al=new ArrayList<Student>();
• al.add(new Student(101,"Vijay",23));
• al.add(new Student(106,"Ajay",27));
• al.add(new Student(105,"Jai",21));
•
• System.out.println("Sorting by Name");
•
• Collections.sort(al,new NameComparator());
• for(Student st: al){
• System.out.println(st.rollno+" "+st.name+" "+st.age);
• }
•
• System.out.println("Sorting by age");
•
• Collections.sort(al,new AgeComparator());
• for(Student st: al){
• System.out.println(st.rollno+" "+st.name+" "+st.age);
• }
• }
• }
• Sorting by Name 106 Ajay 27 105 Jai 21 101
Vijay 23 Sorting by age 105 Jai 21 101 Vijay 23
106 Ajay 27