Map Interface - AJ
Map Interface - AJ
A Map stores data in key and value association. Both key and values are objects. The key
must be unique but the values can be duplicate. Although Maps are a part of Collection
Framework, they can not actually be called as collections because of some properties that
they posses. However we can obtain a collection-view of maps.
Interface Description
Method Description
void putAll(Map map) It is used to insert the specified map in the map.
boolean remove(Object key, It removes the specified values with the associated
Object value) specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
boolean equals(Object o) It is used to compare the specified Object with the Map.
boolean isEmpty() This method returns true if the map is empty; returns false
if it contains at least one key.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, It replaces the old value with the new value for a specified
V newValue) key.
int size() This method returns the number of entries in the map.
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.
Method Description
V setValue(V value) It is used to replace the value corresponding to this entry with the
specified value.
boolean equals(Object It is used to compare the specified object with the other existing
o) objects.
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be
unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform
operations using the key index like updation, deletion, etc. HashMap class is found in the java.util package.
Constructor Description
HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements of
extends V> m) the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the
given integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of the
loadFactor) hash map by using its arguments.
Method Description
void clear() It is used to remove all of the mappings from this map.
Set keySet() It is used to return a set view of the keys contained in this
map.
void putAll(Map map) It is used to insert the specified map in the map.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.
boolean containsValue(Object This method returns true if some value equal to the value
value) exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key
exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
boolean isEmpty() This method returns true if the map is empty; returns false
if it contains at least one key.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, It replaces the old value with the new value for a specified
V newValue) key.
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
It maintains no order.
Java LinkedHashMap contains values based on the key.Java LinkedHashMap contains unique elements.Java
LinkedHashMap may have one null key and multiple null values.Java LinkedHashMap is non synchronized.
Constructor Description
LinkedHashMap(int capacity, float It is used to initialize both the capacity and the
loadFactor) load factor.
LinkedHashMap(int capacity, float It is used to initialize both the capacity and the
loadFactor, boolean accessOrder) load factor with specified ordering mode.
LinkedHashMap(Map<? extends K,? extends It is used to initialize the LinkedHashMap with the
V> m) elements from the given Map class m.
Method Description
V get(Object key) It returns the value to which the specified key is mapped.
boolean containsValue(Object It returns true if the map maps one or more keys to the
value) specified value.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped or
defaultValue) defaultValue if this map contains no mapping for the key.
Set<K> keySet() It returns a Set view of the keys contained in the map
import java.util.*;
class LinkedHashMap2{
public static void main(String args[]){
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Fetching key
System.out.println("Keys: "+map.keySet());
//Fetching value
System.out.println("Values: "+map.values());
//Fetching key-value pair
System.out.println("Key-Value pairs: "+map.entrySet());
}
}
It is same as HashMap instead maintains insertion order.
Java TreeMap class
It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains values based on the
key. 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.
Constructor Description
TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will be
comparator) sorted using the comparator comp.
TreeMap(Map<? extends K,? It is used to initialize a treemap with the entries from m,
extends V> m) which will be sorted using the natural order of the keys.
TreeMap(SortedMap<K,? extends It is used to initialize a treemap with the entries from the
V> m) SortedMap sm, which will be sorted in the same order
as sm.
Method Description
V put(K key, V value) It inserts the specified value with the specified key in the
map.
void putAll(Map<? extends K,? It is used to copy all the key-value pair from one map to
extends V> map) another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super It replaces each entry's value with the result of invoking
K,? super V,? extends V> function) the given function on that entry until all entries have
been processed or the function throws an exception.
boolean containsKey(Object key) It returns true if the map contains a mapping for the
specified key.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the
specified value.
V get(Object key) It is used to return the value to which the map maps the
specified key.
V remove(Object key) It removes the key-value pair of the specified key from
the map.
import java.util.*;
public class TreeMap2 {
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");
System.out.println("Before invoking remove() method");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
map.remove(102);
System.out.println("After invoking remove() method");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
It is same as HashMap instead maintains ascending order(Sorted using the natural order of its key).
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.
Method Description
public int compare(Object It compares the first object with the second object. It returns zero
obj1, Object obj2) if objects are equal. It returns a positive value if obj1>obj2 else
negative
public boolean It is used to compare the current object with the specified object.
equals(Object obj)
import java.util.*;
class Student{
String name;
float percentage;
Collections.sort(studList, com);
Collections algorithm:
The java collection framework defines several algorithms as static methods that can be used with collections and
map objects.
All the collection algorithms in the java are defined in a class called Collections which defined in
the java.util package.
All these algorithms are highly efficient and make coding very easy. It is better to use them than trying to re-
implement them.
Method Description
void sort(List list) Sorts the elements of the list as determined by their natural
ordering.
void sort(List list, Comparator comp) Sorts the elements of the list as determined by Comparator comp.
void rotate(List list, int n) Rotates list by n places to the right. To rotate left, use a negative
value for n.
void copy(List list1, List list2) Copies the elements of list2 to list1.
List nCopies(int num, Object obj) Returns num copies of obj contained in an immutable list. num can
not be zero or negative.
void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices specified by idx1
and idx2.
int binarySearch(List list, Object value) Returns the position of value in the list (must be in the sorted
order), or -1 if value is not found.
int binarySearch(List list, Object value, Returns the position of value in the list ordered according to c, or
Comparator c) -1 if value is not found.
int indexOfSubList(List list, List subList) Returns the index of the first match of subList in the list, or -1 if no
match is found.
int lastIndexOfSubList(List list, List subList) Returns the index of the last match of subList in the list, or -1 if no
match is found.
Object max(Collection c) Returns the largest element from the collection c as determined by
natural ordering.
Object max(Collection c, Comparator Returns the largest element from the collection c as determined by
comp) Comparator comp.
Object min(Collection c) Returns the smallest element from the collection c as determined
by natural ordering.
Object min(Collection c, Comparator comp) Returns the smallest element from the collection c as determined
by Comparator comp.
void fill(List list, Object obj) Assigns obj to each element of the list.
boolean replaceAll(List list, Object old, Replaces all occurrences of old with new in the list.
Object new)
import java.util.*;
public class CollectionAlgorithmsExample {
Collections.sort(list);
System.out.println("List in ascending order => " + list);
Collections.reverse(list);
System.out.println("List in reverse order => " + list);
Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}
The java collection framework has a class Arrays that provides methods for creating dynamic array and perform
various operations like search, asList, campare, etc.
The Arrays class in java is defined in the java.util package. All the methods defined by Arrays class are static
methods.
The Arrays class in java has the following methods.
Method Description
List<T> asList(T[] arr) It returns a fixed-size list backed by the specified Arrays.
int binarySearch(T[] arr, It searches for the specified element in the array with the help of Binary Search
element) algorithm, and returns the position.
boolean equals(T[] arr1, T[] It returns true if the two specified arrays of booleans are equal to one another,
arr2) otherwise retruns false.
void fill(T[] arr, T value) It assigns the specified value to each element of the specified array.
void sort(T[] arr) It sorts the specified array into ascending order.
import java.util.Arrays;
// Main class
class GFG {
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
int intArr1[] = { 10, 15, 22 };
}
}
1 Stack( )
It pushes the element onto the stack and returns the same.
2 Object pop( )
It returns the element on the top of the stack and removes the same.
4 Object peek( )
It returns the element on the top of the stack.
5 boolean empty()
S.No. Methods with Description
import java.util.*;
Dictionary in java
n java, the package java.util contains a class called Dictionary which works like a Map. The Dictionary is an abstract
class used to store and manage elements in the form of a pair of key and value.
The Dictionary stores data as a pair of key and value. In the dictionary, each key associates with a value. We can use
the key to retrieve the value back when needed.
The Dictionary class in java has the following methods.
S.
No. Methods with Description
1 Dictionary( )
It's a constructor.
Inserts a key and its value into the dictionary. Returns null on success; returns the previous value
associated with the key if the key is already exist.
5 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
6 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise returns false.
8 int size( )
It returns the total number of elements in the dictionary.
import java.util.*;
// keys()
System.out.print("\nKeys in Dictionary\n=> ");
for (Enumeration i = dict.keys(); i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}
// elements()
System.out.print("\n\nValues in Dictionary\n=> ");
for (Enumeration i = dict.elements(); i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}
//get()
System.out.println("\n\nValue associated with key 3 => " + dict.get(3));
System.out.println("Value associated with key 30 => " + dict.get(30));
//size()
System.out.println("\nDictionary has " + dict.size() + " elements");
//isEmpty()
System.out.println("\nIs Dictionary empty? " + dict.isEmpty());
}
}
1 Hashtable( )
2 Hashtable(int capacity)
It creates an empty hashtable with the specified initial capacity.
4 Hashtable(Map m)
It creates a hashtable containing elements of Map m.
It inserts the specified key and value into the hash table.
5 V get(Object key)
It returns the value associated with the given key.
6 Enumeration keys()
Returns an enumeration of the keys of the hashtable.
7 Set keySet()
Returns a set view of the keys of the hashtable.
9 Enumeration elements()
Returns an enumeration of the values of the hashtable.
10 Set entrySet()
It returns a set view of the mappings contained in the hashtable.
11 int hashCode()
It returns the hash code of the hashtable.
S. No. Methods with Description
12 Object clone()
It returns a shallow copy of the Hashtable.
21 void rehash()
It is used to increase the size of the hash table and rehashes all of its keys.
26 int size( )
It returns the total number of elements in the Hashtable.
27 void clear()
It is used to remove all the lements of a Hashtable.
28 boolean equals(Object o)
It is used to compare the specified Object with the Hashtable.
Example
import java.util.*;
//get(key)
System.out.println("\nValue associated with key 3 => " + table.get(3));
System.out.println("Value associated with key 30 => " + table.get(30));
//keySet()
System.out.println("\nKeys => " + table.keySet());
//values()
System.out.println("\nValues => " + table.values());
//entrySet()
System.out.println("\nKey, Value pairs as a set => " + table.entrySet());
//hashCode()
System.out.println("\nHash code => " + table.hashCode());
//size()
System.out.println("\nTotal number of elements => " + table.size());
//isEmpty()
System.out.println("\nEmpty status of Hashtable => " + table.isEmpty());
}
}