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.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
Class | Description |
HashMap | HashMap is the implementation of Map, but it doesn't maintain any order. |
LinkedHashMap | LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order. |
TreeMap | TreeMap is the implementation of Map and SortedMap. It maintains ascending order. |
Useful methods of Map interface
Method | Description |
V put(Object key, Object value) | It is used to insert an entry in the map. |
void putAll(Map map) | It is used to insert the specified map in the map. |
V putIfAbsent(K key, V value) | It inserts the specified value with the specified key in the map only if it is not already specified. |
V remove(Object key) | It is used to delete an entry for the specified key. |
boolean remove(Object key, Object value) | It removes the specified values with the associated specified keys from the map. |
Set keySet() | It returns the Set view containing all the keys. |
Set<Map.Entry<K,V>> entrySet() | It returns the Set view containing all the keys and values. |
void clear() | It is used to reset the map. |
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. |
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. |
boolean containsValue(Object value) | This method returns true if some value equal to the 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. |
void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V get(Object key) | This method returns the object that contains the value associated with the key. |
V getOrDefault(Object key, V defaultValue) | It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. |
int hashCode() | It returns the hash code value for the Map |
boolean isEmpty() | This method returns true if the map is empty; returns false if it contains at least one key. |
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
V replace(K key, V value) | It replaces the specified value for a specified key. |
boolean replace(K key, V oldValue, V newValue) | It replaces the old value with the new value for a specified key. |
void replaceAll(BiFunction<? super K,? super V,? extends V> function) | It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
Collection values() | It returns a collection view of the values contained in the map. |
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.
Methods of Map.Entry interface
Method | Description |
K getKey() | It is used to obtain a key. |
V getValue() | It is used to obtain value. |
int hashCode() | It is used to obtain hashCode. |
V setValue(V value) | It is used to replace the value corresponding to this entry with the specified value. |
boolean equals(Object o) | It is used to compare the specified object with the other existing objects. |
static <K extends Comparable<? super K>,V> Comparator<Map.Entry<K,V>> comparingByKey() | It returns a comparator that compare the objects in natural order on key. |
static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp) | It returns a comparator that compare the objects by key using the given Comparator. |
static <K,V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() | It returns a comparator that compare the objects in natural order on value. |
static <K,V> Comparator<Map.Entry<K,V>> comparingByValue(Comparator<? super V> cmp) | It returns a comparator that compare the objects by value using the given Comparator. |
Java Map Example: Non-Generic (Old Style)
//Non-generic
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());
}
}
}
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
Java Map Example: Generic (New Style)
import java.util.*;
class MapExample2{
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
Java Map Example: comparingByKey()
import java.util.*;
class MapExample3{
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");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey())
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
100=Amit
101=Vijay
102=Rahul
Java Map Example: comparingByKey() in Descending Order
import java.util.*;
class MapExample4{
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");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
102=Rahul
101=Vijay
100=Amit
Java Map Example: comparingByValue()
import java.util.*;
class MapExample5{
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");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByValue())
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
100=Amit
102=Rahul
101=Vijay
Java Map Example: comparingByValue() in Descending Order
import java.util.*;
class MapExample6{
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");
//Returns a Set view of the mappings contained in this map
map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
101=Vijay
102=Rahul
100=Amit
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.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and implements the Map interface.
Points to remember
Java HashMap contains values based on the key.
Java HashMap contains only unique keys.
Java HashMap may have one null key and multiple null values.
Java HashMap is non synchronized.
Java HashMap maintains no order.
The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Hierarchy of HashMap class
As shown in the above figure, HashMap class extends AbstractMap class and implements Map interface.
HashMap class declaration
Let's see the declaration for java.util.HashMap class.
- public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
HashMap class Parameters
Let's see the Parameters for java.util.HashMap class.
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java HashMap class
Constructor | Description |
HashMap()---> | It is used to construct a default HashMap. |
HashMap(Map<? extends K,? extends V> m) | It is used to initialize the hash map by using the elements of 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 loadFactor)--> | It is used to initialize both the capacity and load factor of the hash map by using its arguments. |
Methods of Java HashMap class
Method | Description |
void clear() | It is used to remove all of the mappings from this map. |
boolean isEmpty() | It is used to return true if this map contains no key-value mappings. |
Object clone() | It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned. |
Set entrySet() | It is used to return a collection view of the mappings contained in this map. |
Set keySet() | It is used to return a set view of the keys contained in this map. |
V put(Object key, Object value) | It is used to insert an entry in the map. |
void putAll(Map map) | It is used to insert the specified map in the map. |
V putIfAbsent(K key, V value) | It inserts the specified value with the specified key in the map only if it is not already specified. |
V remove(Object key) | It is used to delete an entry for the specified key. |
boolean remove(Object key, Object value) | It removes the specified values with the associated specified keys from the map. |
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. |
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. |
boolean containsValue(Object value) | This method returns true if some value equal to the 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. |
void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V get(Object key) | This method returns the object that contains the value associated with the key. |
V getOrDefault(Object key, V defaultValue) | It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. |
boolean isEmpty() | This method returns true if the map is empty; returns false if it contains at least one key. |
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
V replace(K key, V value) | It replaces the specified value for a specified key. |
boolean replace(K key, V oldValue, V newValue) | It replaces the old value with the new value for a specified key. |
void replaceAll(BiFunction<? super K,? super V,? extends V> function) | It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
Collection<V> values() | It returns a collection view of the values contained in the map. |
int size() | This method returns the number of entries in the map. |
Java HashMap Example
Let's see a simple example of HashMap to store key and value pair.
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());
}
}
}
Iterating Hashmap... 1 Mango 2 Apple 3 Banana 4 Grapes
In this example, we are storing Integer as the key and String as the value, so we are using HashMap<Integer,String> as the type. The put() method inserts the elements in the map.
To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry.
No Duplicate Key on HashMap
You cannot store duplicate keys in HashMap. However, if you try to store duplicate key with another value, it will replace the value.
import java.util.*;
public class HashMapExample2{
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(1,"Grapes"); //trying duplicate key
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Iterating Hashmap... 1 Grapes 2 Apple 3 Banana
Java HashMap example to add() elements
Here, we see different ways to insert elements.
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());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
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
After invoking putAll() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
Java HashMap example to remove() elements
Here, we see different ways to remove elements.
import java.util.*;
public class HashMap2 {
public static void main(String args[]) {
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(103, "Gaurav");
System.out.println("Initial list of elements: "+map);
//key-based removal
map.remove(100);
System.out.println("Updated list of elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Updated list of elements: "+map);
//key-value pair based removal
map.remove(102, "Rahul");
System.out.println("Updated list of elements: "+map);
}
}
Output:
Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav} Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav} Updated list of elements: {102=Rahul, 103=Gaurav} Updated list of elements: {103=Gaurav}
Java HashMap example to replace() elements
Here, we see different ways to replace elements.
import java.util.*;
class HashMap3{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
System.out.println("Initial list of elements:");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(102, "Gaurav");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(101, "Vijay", "Ravi");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replaceAll((k,v) -> "Ajay");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay
Difference between HashSet and HashMap
HashSet contains only values whereas HashMap contains an entry(key and value).
Java 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);
}
}
}
Output:
1 Details: 101 Let us C Yashwant Kanetkar BPB 8 2 Details: 102 Data Communications and Networking Forouzan Mc Graw Hill 4 3 Details: 103 Operating System Galvin Wiley 6
Working of HashMap in Java
What is Hashing
It is the process of converting an object into an integer value. The integer value helps in indexing and faster searches.
What is HashMap ?
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.
Before understanding the internal working of HashMap, you must be aware of hashCode() and equals() method.
equals(): It checks the equality of two objects. It compares the Key, whether they are equal or not. It is a method of the Object class. It can be overridden. If you override the equals() method, then it is mandatory to override the hashCode() method.
hashCode(): This is the method of the object class. It returns the memory reference of the object in integer form. The value received from the method is used as the bucket number. The bucket number is the address of the element inside the map. Hash code of null Key is 0.
Buckets: Array of the node is called buckets. Each node has a data structure like a LinkedList. More than one node can share the same bucket. It may be different in capacity.
Insert Key, Value pair in HashMap
We use put() method to insert the Key and Value pair in the HashMap. The default size of HashMap is 16 (0 to 15).
Example
In the following example, we want to insert three (Key, Value) pair in the HashMap.
HashMap<String, Integer> map = new HashMap<>();
map.put("Aman", 19);
map.put("Sunny", 29);
map.put("Ritesh", 39);
Let's see at which index the Key, value pair will be saved into HashMap. When we call the put() method, then it calculates the hash code of the Key "Aman." Suppose the hash code of "Aman" is 2657860. To store the Key in memory, we have to calculate the index.
Calculating Index
Index minimizes the size of the array. The Formula for calculating the index is:
- Index = hashcode(Key) & (n-1)
Where n is the size of the array. Hence the index value for "Aman" is:
- Index = 2657860 & (16-1) = 4
The value 4 is the computed index value where the Key and value will store in HashMap.
Hash Collision
This is the case when the calculated index value is the same for two or more Keys. Let's calculate the hash code for another Key "Sunny." Suppose the hash code for "Sunny" is 63281940. To store the Key in the memory, we have to calculate index by using the index formula.
- Index=63281940 & (16-1) = 4
The value 4 is the computed index value where the Key will be stored in HashMap. In this case, equals() method check that both Keys are equal or not. If Keys are same, replace the value with the current value. Otherwise, connect this node object to the existing node object through the LinkedList. Hence both Keys will be stored at index 4.
Similarly, we will store the Key "Ritesh." Suppose hash code for the Key is 2349873. The index value will be 1. Hence this Key will be stored at index 1.
Working of HashMap in Java
What is Hashing
It is the process of converting an object into an integer value. The integer value helps in indexing and faster searches.
What is HashMap
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.--
Before understanding the internal working of HashMap, you must be aware of hashCode() and equals() method.
equals(): It checks the equality of two objects. It compares the Key, whether they are equal or not. It is a method of the Object class. It can be overridden. If you override the equals() method, then it is mandatory to override the hashCode() method.
hashCode(): This is the method of the object class. It returns the memory reference of the object in integer form. The value received from the method is used as the bucket number. The bucket number is the address of the element inside the map. Hash code of null Key is 0.
Buckets: Array of the node is called buckets. Each node has a data structure like a LinkedList. More than one node can share the same bucket. It may be different in capacity.
Insert Key, Value pair in HashMap
We use put() method to insert the Key and Value pair in the HashMap. The default size of HashMap is 16 (0 to 15).
Example
In the following example, we want to insert three (Key, Value) pair in the HashMap.
HashMap<String, Integer> map = new HashMap<>();
map.put("Aman", 19);
map.put("Sunny", 29);
map.put("Ritesh", 39);
Let's see at which index the Key, value pair will be saved into HashMap. When we call the put() method, then it calculates the hash code of the Key "Aman." Suppose the hash code of "Aman" is 2657860. To store the Key in memory, we have to calculate the index.
Calculating Index
Index minimizes the size of the array. The Formula for calculating the index is:
- Index = hashcode(Key) & (n-1)
Where n is the size of the array. Hence the index value for "Aman" is:
- Index = 2657860 & (16-1) = 4
The value 4 is the computed index value where the Key and value will store in HashMap.
Hash Collision
This is the case when the calculated index value is the same for two or more Keys. Let's calculate the hash code for another Key "Sunny." Suppose the hash code for "Sunny" is 63281940. To store the Key in the memory, we have to calculate index by using the index formula.
- Index=63281940 & (16-1) = 4
The value 4 is the computed index value where the Key will be stored in HashMap. In this case, equals() method check that both Keys are equal or not. If Keys are same, replace the value with the current value. Otherwise, connect this node object to the existing node object through the LinkedList. Hence both Keys will be stored at index 4.
Similarly, we will store the Key "Ritesh." Suppose hash code for the Key is 2349873. The index value will be 1. Hence this Key will be stored at index 1.
get() method in HashMap
get() method is used to get the value by its Key. It will not fetch the value if you don't know the Key. When get(K Key) method is called, it calculates the hash code of the Key.
Suppose we have to fetch the Key "Aman." The following method will be called.
- map.get(new Key("Aman"));
It generates the hash code as 2657860. Now calculate the index value of 2657860 by using index formula. The index value will be 4, as we have calculated above. get() method search for the index value 4. It compares the first element Key with the given Key. If both keys are equal, then it returns the value else check for the next element in the node if it exists. In our scenario, it is found as the first element of the node and return the value 19.
Let's fetch another Key "Sunny."
The hash code of the Key "Sunny" is 63281940. The calculated index value of 63281940 is 4, as we have calculated for put() method. Go to index 4 of the array and compare the first element's Key with the given Key. It also compares Keys. In our scenario, the given Key is the second element, and the next of the node is null. It compares the second element Key with the specified Key and returns the value 29. It returns null if the next of the node is null.
Java LinkedHashMap class
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.
Points to remember
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.
Java LinkedHashMap maintains insertion order.
The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
LinkedHashMap class declaration
Let's see the declaration for java.util.LinkedHashMap class.
- public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
LinkedHashMap class Parameters
Let's see the Parameters for java.util.LinkedHashMap class.
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java LinkedHashMap class
Constructor | Description |
LinkedHashMap() | It is used to construct a default LinkedHashMap. |
LinkedHashMap(int capacity) | It is used to initialize a LinkedHashMap with the given capacity. |
LinkedHashMap(int capacity, float loadFactor) | It is used to initialize both the capacity and the load factor. |
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) | It is used to initialize both the capacity and the load factor with specified ordering mode. |
LinkedHashMap(Map<? extends K,? extends V> m) | It is used to initialize the LinkedHashMap with the elements from the given Map class m. |
Methods of Java LinkedHashMap class
Method | Description |
V get(Object key) | It returns the value to which the specified key is mapped. |
void clear() | It removes all the key-value pairs from a map. |
boolean containsValue(Object value) | It returns true if the map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> entrySet() | It returns a Set view of the mappings contained in the map. |
void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V getOrDefault(Object key, V defaultValue) | It returns the value to which the specified key is mapped or 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 |
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) | It returns true on removing its eldest entry. |
void replaceAll(BiFunction<? super K,? super V,? extends V> function) | It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
Collection<V> values() | It returns a Collection view of the values contained in this map. |
Java LinkedHashMap Example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:100 Amit
101 Vijay
102 Rahul
Java LinkedHashMap Example: Key-Value pair
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());
}
}
Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]
Java LinkedHashMap Example:remove()
import java.util.*;
public class LinkedHashMap3 {
public static void main(String args[]) {
Map<Integer,String> map=new LinkedHashMap<Integer,String>();
map.put(101,"Amit");
map.put(102,"Vijay");
map.put(103,"Rahul");
System.out.println("Before invoking remove() method: "+map);
map.remove(102);
System.out.println("After invoking remove() method: "+map);
}
}
Output:
Before invoking remove() method: {101=Amit, 102=Vijay, 103=Rahul} After invoking remove() method: {101=Amit, 103=Rahul}
Java LinkedHashMap 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 LinkedHashMap<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(2,b2);
map.put(1,b1);
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);
}
}
}
Output:
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6
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.
TreeMap class declaration
Let's see the declaration for java.util.TreeMap class.
- public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable
TreeMap class Parameters
Let's see the Parameters for java.util.TreeMap class.
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java TreeMap class
| Constructor | 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> comparator) | It is used to construct an empty tree-based map that will be sorted using the comparator comp. | | TreeMap(Map<? extends K,? extends V> m) | It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys. | | TreeMap(SortedMap<K,? extends V> m) | It is used to initialize a treemap 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 key) | It returns the key-value pair 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 K> comparator() | It returns the comparator that arranges the key in order, or null if the map uses the natural ordering. | | NavigableSet<K> descendingKeySet() | It returns a reverse order NavigableSet view of the keys contained in the map. | | NavigableMap<K,V> descendingMap() | It returns the specified key-value pairs in descending order. | | Map.Entry firstEntry() | It returns the key-value pair having the least key. | | Map.Entry<K,V> floorEntry(K key) | It returns the greatest key, less than or equal to the specified key, or null if there is no such key. | | void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. | | SortedMap<K,V> headMap(K toKey) | It returns the key-value pairs whose keys are strictly less than toKey. | | NavigableMap<K,V> headMap(K toKey, boolean inclusive) | It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey. | | Map.Entry<K,V> higherEntry(K key) | It returns the least key strictly greater than the given key, or null if there is no such key. | | K higherKey(K key) | It is used to return true if this map contains a mapping for the specified key. | | Set keySet() | It returns the collection of keys exist in the map. | | Map.Entry<K,V> lastEntry() | It returns the key-value pair having the greatest key, or null if there is no such key. | | Map.Entry<K,V> lowerEntry(K key) | It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. | | K lowerKey(K key) | It returns the greatest key strictly less than the given key, or null if there is no such key. | | NavigableSet<K> navigableKeySet() | It returns a NavigableSet view of the keys contained in this map. | | Map.Entry<K,V> pollFirstEntry() | It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. | | Map.Entry<K,V> pollLastEntry() | It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. | | V put(K key, V value) | It inserts the specified value with the specified key in the map. | | void putAll(Map<? extends K,? extends V> map) | It is used to copy all the key-value pair from one map to another map. | | V replace(K key, V value) | It replaces the specified value for a specified key. | | boolean replace(K key, V oldValue, V newValue) | It replaces the old value with the new value for a specified key. | | void replaceAll(BiFunction<? super K,? super V,? extends V> function) | It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. | | NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) | It returns key-value pairs whose keys range from fromKey to toKey. | | SortedMap<K,V> subMap(K fromKey, K toKey) | It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive. | | SortedMap<K,V> tailMap(K fromKey) | It returns key-value pairs whose keys are greater than or equal to fromKey. | | NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) | It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey. | | 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. | | K firstKey() | It is used to return the first (lowest) key currently in this sorted map. | | V get(Object key) | It is used to return the value to which the map maps the specified key. | | K lastKey() | It is used to return the last (highest) key currently in the sorted map. | | V remove(Object key) | It removes the key-value pair of the specified key from the map. | | Set<Map.Entry<K,V>> entrySet() | It returns a set view of the mappings contained in the map. | | 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. |
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:100 Amit
101 Vijay
102 Ravi
103 Rahul
Java TreeMap Example: remove()
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());
}
}
}
Output:
Before invoking remove() method
100 Amit
101 Vijay
102 Ravi
103 Rahul
After invoking remove() method
100 Amit
101 Vijay
103 Rahul
Java TreeMap Example: NavigableMap
import java.util.*;
class TreeMap3{
public static void main(String args[]){
NavigableMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Maintains descending order
System.out.println("descendingMap: "+map.descendingMap());
//Returns key-value pairs whose keys are less than or equal to the specified key.
System.out.println("headMap: "+map.headMap(102,true));
//Returns key-value pairs whose keys are greater than or equal to the specified key.
System.out.println("tailMap: "+map.tailMap(102,true));
//Returns key-value pairs exists in between the specified key.
System.out.println("subMap: "+map.subMap(100, false, 102, true));
}
}
descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
headMap: {100=Amit, 101=Vijay, 102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}
Java TreeMap Example: SortedMap
import java.util.*;
class TreeMap4{
public static void main(String args[]){
SortedMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Returns key-value pairs whose keys are less than the specified key.
System.out.println("headMap: "+map.headMap(102));
//Returns key-value pairs whose keys are greater than or equal to the specified key.
System.out.println("tailMap: "+map.tailMap(102));
//Returns key-value pairs exists in between the specified key.
System.out.println("subMap: "+map.subMap(100, 102));
}
}
headMap: {100=Amit, 101=Vijay}
tailMap: {102=Ravi, 103=Rahul}
subMap: {100=Amit, 101=Vijay}
What is difference between HashMap and TreeMap?
HashMap | TreeMap |
1) HashMap can contain one null key. | TreeMap cannot contain any null key. |
2) HashMap maintains no order. | TreeMap maintains ascending order. |
Java TreeMap 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 TreeMap<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(2,b2);
map.put(1,b1);
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);
}
}
}
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface.
Points to remember
A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
Java Hashtable class contains unique elements.
Java Hashtable class doesn't allow null key or value.
Java Hashtable class is synchronized.
The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Hashtable class declaration
Let's see the declaration for java.util.Hashtable class.
- public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable
Hashtable class Parameters
Let's see the Parameters for java.util.Hashtable class.
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java Hashtable class
Constructor | Description |
Hashtable() | It creates an empty hashtable having the initial default capacity and load factor. |
Hashtable(int capacity) | It accepts an integer parameter and creates a hash table that contains a specified initial capacity. |
Hashtable(int capacity, float loadFactor) | It is used to create a hash table having the specified initial capacity and loadFactor. |
Hashtable(Map<? extends K,? extends V> t) | It creates a new hash table with the same mappings as the given Map. |
Methods of Java Hashtable class
Method | Description |
void clear() | It is used to reset the hash table. |
Object clone() | It returns a shallow copy of the Hashtable. |
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. |
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. |
Enumeration elements() | It returns an enumeration of the values in the hash table. |
Set<Map.Entry<K,V>> entrySet() | It returns a set view of the mappings contained in the map. |
boolean equals(Object o) | It is used to compare the specified Object with the Map. |
void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V getOrDefault(Object key, V defaultValue) | It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. |
int hashCode() | It returns the hash code value for the Map |
Enumeration<K> keys() | It returns an enumeration of the keys in the hashtable. |
Set<K> keySet() | It returns a Set view of the keys contained in the map. |
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
V put(K key, V value) | It inserts the specified value with the specified key in the hash table. |
void putAll(Map<? extends K,? extends V> t)) | It is used to copy all the key-value pair from map to hashtable. |
V putIfAbsent(K key, V value) | If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value. |
boolean remove(Object key, Object value) | It removes the specified values with the associated specified keys from the hashtable. |
V replace(K key, V value) | It replaces the specified value for a specified key. |
boolean replace(K key, V oldValue, V newValue) | It replaces the old value with the new value for a specified key. |
void replaceAll(BiFunction<? super K,? super V,? extends V> function) | It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
String toString() | It returns a string representation of the Hashtable object. |
Collection values() | It returns a collection view of the values contained in the map. |
boolean contains(Object value) | This method returns true if some value equal to the value exists within the hash table, else return false. |
boolean containsValue(Object value) | This method returns true if some value equal to the value exists within the hash table, else return false. |
boolean containsKey(Object key) | This method return true if some key equal to the key exists within the hash table, else return false. |
boolean isEmpty() | This method returns true if the hash table is empty; returns false if it contains at least one key. |
protected void rehash() | It is used to increase the size of the hash table and rehashes all of its keys. |
V get(Object key) | This method returns the object that contains the value associated with the key. |
V remove(Object key) | It is used to remove the key and its value. This method returns the value associated with the key. |
int size() | This method returns the number of entries in the hash table. |
Java Hashtable Example
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul 102 Ravi 101 Vijay 100 Amit
Java Hashtable Example: remove()
import java.util.*;
public class Hashtable2 {
public static void main(String args[]) {
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("After remove: "+ map);
}
}
Output:
Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
After remove: {103=Rahul, 101=Vijay, 100=Amit}
Java Hashtable Example: getOrDefault()
import java.util.*;
class Hashtable3{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Here, we specify the if and else statement as arguments of the method
System.out.println(map.getOrDefault(101, "Not Found"));
System.out.println(map.getOrDefault(105, "Not Found"));
}
}
Output:
Vijay
Not Found
Java Hashtable Example: putIfAbsent()
import java.util.*;
class Hashtable4{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Initial Map: "+map);
//Inserts, as the specified pair is unique
map.putIfAbsent(104,"Gaurav");
System.out.println("Updated Map: "+map);
//Returns the current value, as the specified pair already exist
map.putIfAbsent(101,"Vijay");
System.out.println("Updated Map: "+map);
}
}
Output:
Initial Map: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Updated Map: {104=Gaurav, 103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Updated Map: {104=Gaurav, 103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Java Hashtable 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 HashtableExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new Hashtable<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);
}
}
}
Output:
3 Details:
103 Operating System Galvin Wiley 6
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
Difference between HashMap and Hashtable
HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap | Hashtable |
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code. | Hashtable is synchronized. It is thread-safe and can be shared with many threads. |
2) HashMap allows one null key and multiple null values. | Hashtable doesn't allow any null key or value. |
3) HashMap is a new class introduced in JDK 1.2. | Hashtable is a legacy class. |
4) HashMap is fast. | Hashtable is slow. |
5) We can make the HashMap as synchronized by calling this code | |
Map m = Collections.synchronizedMap(hashMap); | Hashtable is internally synchronized and can't be unsynchronized. |
6) HashMap is traversed by Iterator. | Hashtable is traversed by Enumerator and Iterator. |
7) Iterator in HashMap is fail-fast. | Enumerator in Hashtable is not fail-fast. |
8) HashMap inherits AbstractMap class. | Hashtable inherits Dictionary class. |
TUESDAY
WEDNESDAY
Java EnumSet Example: allOf() and noneOf()
import java.util.*;
enum days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
public static void main(String[] args) {
Set<days> set1 = EnumSet.allOf(days.class);
System.out.println("Week Days:"+set1);
Set<days> set2 = EnumSet.noneOf(days.class);
System.out.println("Week Days:"+set2);
}
}
Output:
Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Week Days:[]
Java EnumMap class
Java EnumMap class is the specialized Map implementation for enum keys. It inherits Enum and AbstractMap classes.
EnumMap class hierarchy
The hierarchy of EnumMap class is given in the figure given below.
EnumMap class declaration
Let's see the declaration for java.util.EnumMap class.
- public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable
EnumMap class Parameters
Let's see the Parameters for java.util.EnumMap class.
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java EnumMap class
Constructor | Description |
EnumMap(Class<K> keyType) | It is used to create an empty enum map with the specified key type. |
EnumMap(EnumMap<K,? extends V> m) | It is used to create an enum map with the same key type as the specified enum map. |
EnumMap(Map<K,? extends V> m) | It is used to create an enum map initialized from the specified map. |
Methods of Java EnumMap class
SN | Method | Description |
1 | clear() | It is used to clear all the mapping from the map. |
2 | clone() | It is used to copy the mapped value of one map to another map. |
3 | containsKey() | It is used to check whether a specified key is present in this map or not. |
4 | containsValue() | It is used to check whether one or more key is associated with a given value or not. |
5 | entrySet() | It is used to create a set of elements contained in the EnumMap. |
6 | equals() | It is used to compare two maps for equality. |
7 | get() | It is used to get the mapped value of the specified key. |
8 | hashCode() | It is used to get the hashcode value of the EnumMap. |
9 | keySet() | It is used to get the set view of the keys contained in the map. |
10 | size() | It is used to get the size of the EnumMap. |
11 | Values() | It is used to create a collection view of the values contained in this map. |
12 | put() | It is used to associate the given value with the given key in this EnumMap. |
13 | putAll() | It is used to copy all the mappings from one EnumMap to a new EnumMap. |
14 | remove() | It is used to remove the mapping for the given key from EnumMap if the given key is present. |
Java EnumMap Example
import java.util.*;
public class EnumMapExample {
// create an enum
public enum Days {
Monday, Tuesday, Wednesday, Thursday
};
public static void main(String[] args) {
//create and populate enum map
EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);
map.put(Days.Monday, "1");
map.put(Days.Tuesday, "2");
map.put(Days.Wednesday, "3");
map.put(Days.Thursday, "4");
// print the map
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Monday 1
Tuesday 2
Wednesday 3
Thursday 4
Java EnumMap 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 EnumMapExample {
// Creating enum
public enum Key{
One, Two, Three
};
public static void main(String[] args) {
EnumMap<Key, Book> map = new EnumMap<Key, Book>(Key.class);
// 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(Key.One, b1);
map.put(Key.Two, b2);
map.put(Key.Three, b3);
// Traversing EnumMap
for(Map.Entry<Key, Book> entry:map.entrySet()){
Book b=entry.getValue();
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Java Collections class
Java collection class is used exclusively with static methods that operate on or return collections. It inherits Object class.
The important points about Java Collections class are:
Java Collection class supports the polymorphic algorithms that operate on collections.
Java Collection class throws a NullPointerException if the collections or class objects provided to them are null.
Collections class declaration
Let's see the declaration for java.util.Collections class.
- public class Collections extends Object
SN | Modifier & Type | Methods | Descriptions |
1) | static <T> boolean | addAll() | It is used to adds all of the specified elements to the specified collection. |
2) | static <T> Queue<T> | asLifoQueue() | It returns a view of a Deque as a Last-in-first-out (LIFO) Queue. |
3) | static <T> int | binarySearch() | It searches the list for the specified object and returns their position in a sorted list. |
4) | static <E> Collection<E> | checkedCollection() | It is used to returns a dynamically typesafe view of the specified collection. |
5) | static <E> List<E> | checkedList() | It is used to returns a dynamically typesafe view of the specified list. |
6) | static <K,V> Map<K,V> | checkedMap() | It is used to returns a dynamically typesafe view of the specified map. |
7) | static <K,V> NavigableMap<K,V> | checkedNavigableMap() | It is used to returns a dynamically typesafe view of the specified navigable map. |
8) | static <E> NavigableSet<E> | checkedNavigableSet() | It is used to returns a dynamically typesafe view of the specified navigable set. |
9) | static <E> Queue<E> | checkedQueue() | It is used to returns a dynamically typesafe view of the specified queue. |
10) | static <E> Set<E> | checkedSet() | It is used to returns a dynamically typesafe view of the specified set. |
11) | static <K,V> SortedMap<K,V> | checkedSortedMap() | It is used to returns a dynamically typesafe view of the specified sorted map. |
12) | static <E> SortedSet<E> | checkedSortedSet() | It is used to returns a dynamically typesafe view of the specified sorted set. |
13) | static <T> void | copy() | It is used to copy all the elements from one list into another list. |
14) | static boolean | disjoint() | It returns true if the two specified collections have no elements in common. |
15) | static <T> Enumeration<T> | emptyEnumeration() | It is used to get an enumeration that has no elements. |
16) | static <T> Iterator<T> | emptyIterator() | It is used to get an Iterator that has no elements. |
17) | static <T> List<T> | emptyList() | It is used to get a List that has no elements. |
18) | static <T> ListIterator<T> | emptyListIterator() | It is used to get a List Iterator that has no elements. |
19) | static <K,V> Map<K,V> | emptyMap() | It returns an empty map which is immutable. |
20) | static <K,V> NavigableMap<K,V> | emptyNavigableMap() | It returns an empty navigable map which is immutable. |
21) | static <E> NavigableSet<E> | emptyNavigableSet() | It is used to get an empty navigable set which is immutable in nature. |
22) | static <T> Set<T> | emptySet() | It is used to get the set that has no elements. |
23) | static <K,V> SortedMap<K,V> | emptySortedMap() | It returns an empty sorted map which is immutable. |
24) | static <E> SortedSet<E> | emptySortedSet() | It is used to get the sorted set that has no elements. |
25) | static <T> Enumeration<T> | enumeration() | It is used to get the enumeration over the specified collection. |
26) | static <T> void | fill() | It is used to replace all of the elements of the specified list with the specified elements. |
27) | static int | frequency() | It is used to get the number of elements in the specified collection equal to the specified object. |
28) | static int | indexOfSubList() | It is used to get the starting position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list. |
29) | static int | lastIndexOfSubList() | It is used to get the starting position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list. |
30) | static <T> ArrayList<T> | list() | It is used to get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration. |
31) | static <T extends Object & Comparable<? super T>> T | max() | It is used to get the maximum value of the given collection, according to the natural ordering of its elements. |
32) | static <T extends Object & Comparable<? super T>> T | min() | It is used to get the minimum value of the given collection, according to the natural ordering of its elements. |
33) | static <T> List<T> | nCopies() | It is used to get an immutable list consisting of n copies of the specified object. |
34) | static <E> Set<E> | newSetFromMap() | It is used to return a set backed by the specified map. |
35) | static <T> boolean | replaceAll() | It is used to replace all occurrences of one specified value in a list with the other specified value. |
36) | static void | reverse() | It is used to reverse the order of the elements in the specified list. |
37) | static <T> Comparator<T> | reverseOrder() | It is used to get the comparator that imposes the reverse of the natural ordering on a collection of objects which implement the Comparable interface. |
38) | static void | rotate() | It is used to rotate the elements in the specified list by a given distance. |
39) | static void | shuffle() | It is used to randomly reorders the specified list elements using a default randomness. |
40) | static <T> Set<T> | singleton() | It is used to get an immutable set which contains only the specified object. |
41) | static <T> List<T> | singletonList() | It is used to get an immutable list which contains only the specified object. |
42) | static <K,V> Map<K,V> | singletonMap() | It is used to get an immutable map, mapping only the specified key to the specified value. |
43) | static <T extends Comparable<? super T>>void | sort() | It is used to sort the elements presents in the specified list of collection in ascending order. |
44) | static void | swap() | It is used to swap the elements at the specified positions in the specified list. |
45) | static <T> Collection<T> | synchronizedCollection() | It is used to get a synchronized (thread-safe) collection backed by the specified collection. |
46) | static <T> List<T> | synchronizedList() | It is used to get a synchronized (thread-safe) collection backed by the specified list. |
47) | static <K,V> Map<K,V> | synchronizedMap() | It is used to get a synchronized (thread-safe) map backed by the specified map. |
48) | static <K,V> NavigableMap<K,V> | synchronizedNavigableMap() | It is used to get a synchronized (thread-safe) navigable map backed by the specified navigable map. |
49) | static <T> NavigableSet<T> | synchronizedNavigableSet() | It is used to get a synchronized (thread-safe) navigable set backed by the specified navigable set. |
50) | static <T> Set<T> | synchronizedSet() | It is used to get a synchronized (thread-safe) set backed by the specified set. |
51) | static <K,V> SortedMap<K,V> | synchronizedSortedMap() | It is used to get a synchronized (thread-safe) sorted map backed by the specified sorted map. |
52) | static <T> SortedSet<T> | synchronizedSortedSet() | It is used to get a synchronized (thread-safe) sorted set backed by the specified sorted set. |
53) | static <T> Collection<T> | unmodifiableCollection() | It is used to get an unmodifiable view of the specified collection. |
54) | static <T> List<T> | unmodifiableList() | It is used to get an unmodifiable view of the specified list. |
55) | static <K,V> Map<K,V> | unmodifiableMap() | It is used to get an unmodifiable view of the specified map. |
56) | static <K,V> NavigableMap<K,V> | unmodifiableNavigableMap() | It is used to get an unmodifiable view of the specified navigable map. |
57) | static <T> NavigableSet<T> | unmodifiableNavigableSet() | It is used to get an unmodifiable view of the specified navigable set. |
58) | static <T> Set<T> | unmodifiableSet() | It is used to get an unmodifiable view of the specified set. |
59) | static <K,V> SortedMap<K,V> | unmodifiableSortedMap() | It is used to get an unmodifiable view of the specified sorted map. |
60 | static <T> SortedSet<T> | unmodifiableSortedSet() | It is used to get an unmodifiable view of the specified sorted set. |
Java Collections Example
import java.util.*;
public class CollectionsExample {
public static void main(String a[]){
List<String> list = new ArrayList<String>();
list.add("C");
list.add("Core Java");
list.add("Advance Java");
System.out.println("Initial collection value:"+list);
Collections.addAll(list, "Servlet","JSP");
System.out.println("After adding elements collection value:"+list);
String[] strArr = {"C#", ".Net"};
Collections.addAll(list, strArr);
System.out.println("After adding array collection value:"+list);
}
}
Output:
Initial collection value:[C, Core Java, Advance Java]
After adding elements collection value:[C, Core Java, Advance Java, Servlet, JSP]
After adding array collection value:[C, Core Java, Advance Java, Servlet, JSP, C#, .Net]
Java Collections Example: max()
import java.util.*;
public class CollectionsExample {
public static void main(String a[]){
List<Integer> list = new ArrayList<Integer>();
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
System.out.println("Value of maximum element from the collection: "+Collections.max(list));
}
}
Output:
Value of maximum element from the collection: 67
Java Collections Example: min()
import java.util.*;
public class CollectionsExample {
public static void main(String a[]){
List<Integer> list = new ArrayList<Integer>();
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
System.out.println("Value of minimum element from the collection: "+Collections.min(list));
}
}
Output:
Value of minimum element from the collection: 8
Sorting in Collection
We can sort the elements of:
String objects
Wrapper class objects
User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements. |
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable type.
Note: String class and Wrapper classes implement the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Example to sort string objects
import java.util.*;
class TestSort1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Mukesh
Saurav
Tahir
Viru
Example to sort string objects in reverse order
import java.util.*;
class TestSort2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");
Collections.sort(al,Collections.reverseOrder());
Iterator i=al.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Viru
Tahir
Saurav
Mukesh
Example to sort Wrapper class objects
import java.util.*;
class TestSort3{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);//internally will be converted into objects as Integer.valueOf(230)
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
101
201
230
Example to sort user-defined class objects
import java.util.*;
class Student implements Comparable<Student> {
public String name;
public Student(String name) {
this.name = name;
}
public int compareTo(Student person) {
return name.compareTo(person.name);
}
}
public class TestSort4 {
public static void main(String[] args) {
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student("Viru"));
al.add(new Student("Saurav"));
al.add(new Student("Mukesh"));
al.add(new Student("Tahir"));
Collections.sort(al);
for (Student s : al) {
System.out.println(s.name);
}
}
}
Mukesh
Saurav
Tahir
Viru
Java Comparable interface
Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns
positive integer, if the current object is greater than the specified object.
negative integer, if the current object is less than the specified object.
zero, if the current object is equal to the specified object.
We can sort the elements of:
String objects
Wrapper class objects
User-defined class objects
Collections class
Collections class provides static methods for sorting the elements of collections. If collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
Java Comparable interface
Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns
positive integer, if the current object is greater than the specified object.
negative integer, if the current object is less than the specified object.
zero, if the current object is equal to the specified object.
We can sort the elements of:
String objects
Wrapper class objects
User-defined class objects
Collections class
Collections class provides static methods for sorting the elements of collections. If collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): It is used to sort the elements of List. List elements must be of the Comparable type.
Note: String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.
Java Comparable Example
Let's see the example of the Comparable interface that sorts the list elements on the basis of age.
File: Student.java
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
File: TestSort1.java
import java.util.*;
public class TestSort1{
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));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
105 Jai 21
101 Vijay 23
106 Ajay 27
Java Comparable Example: reverse order
Let's see the same example of the Comparable interface that sorts the list elements on the basis of age in reverse order.
File: Student.java
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age<st.age)
return 1;
else
return -1;
}
}
File: TestSort2.java
import java.util.*;
public class TestSort2{
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));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
106 Ajay 27
101 Vijay 23
105 Jai 21
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. |
Collections class
Collections class provides static methods for sorting the elements of a collection. If collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements also.
Method of Collections class for sorting List elements
public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.
Java Comparator Example (Non-generic Old Style)
Let's see the example of sorting the elements of List on the basis of age and name. In this example, we have created 4 java classes:
This class contains three fields rollno, name and age and a parameterized constructor.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
}
This class defines comparison logic based on the age. If the age of the first object is greater than the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age of the first object is less than the second object, we are returning a negative value, it can be any negative value, and if the age of both objects is equal, we are returning 0.
import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.
import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
}
}
In 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 al=new ArrayList();
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());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("Sorting by age");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
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
Java Comparator Example (Generic)
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
}
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;
}
}
This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.
import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
}
}
In 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
Java 8 Comparator interface
Java 8 Comparator interface is a functional interface that contains only one abstract method. Now, we can use the Comparator interface as the assignment target for a lambda expression or method reference.
Methods of Java 8 Comparator Interface
Method | Description |
int compare(T o1, T o2) | It compares the first object with second object. |
static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor) | It accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key. |
static <T,U> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator) | It accepts a function that extracts a sort key from a type T, and returns a Comparator that compares by that sort key using the specified Comparator. |
static <T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) | It accepts a function that extracts a double sort key from a type T, and returns a Comparator that compares by that sort key. |
static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) | It accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key. |
static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) | It accepts a function that extracts a long sort key from a type T, and returns a Comparator that compares by that sort key. |
boolean equals(Object obj) | It is used to compare the current object with the specified object. |
static <T extends Comparable<? super T>> Comparator<T> naturalOrder() | It returns a comparator that compares Comparable objects in natural order. |
static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) | It returns a comparator that treats null to be less than non-null elements. |
static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) | It returns a comparator that treats null to be greater than non-null elements. |
default Comparator<T> reversed() | It returns comparator that contains reverse ordering of the provided comparator. |
static <T extends Comparable<? super T>> Comparator<T> reverseOrder() | It returns comparator that contains reverse of natural ordering. |
default Comparator<T> thenComparing(Comparator<? super T> other) | It returns a lexicographic-order comparator with another comparator. |
default <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T,? extends U> keyExtractor) | It returns a lexicographic-order comparator with a function that extracts a Comparable sort key. |
default <U> Comparator<T> thenComparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator) | It returns a lexicographic-order comparator with a function that extracts a key to be compared with the given Comparator. |
default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) | It returns a lexicographic-order comparator with a function that extracts a double sort key. |
default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) | It returns a lexicographic-order comparator with a function that extracts a int sort key. |
default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) | It returns a lexicographic-order comparator with a function that extracts a long sort key. |
Java 8 Comparator Example
Let's see the example of sorting the elements of List on the basis of age and name.
File: 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;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
File: TestSort1.java
import java.util.*;
public class TestSort1{
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));
/Sorting elements on the basis of name
Comparator<Student> cm1=Comparator.comparing(Student::getName);
Collections.sort(al,cm1);
System.out.println("Sorting by Name");
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
//Sorting elements on the basis of age
Comparator<Student> cm2=Comparator.comparing(Student::getAge);
Collections.sort(al,cm2);
System.out.println("Sorting by Age");
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
Java 8 Comparator Example: nullsFirst() and nullsLast() method
Here, we sort the list of elements that also contains null.
File: 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;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
File: TestSort2.java
import java.util.*;
public class TestSort2{
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,null,21));
Comparator<Student> cm1=Comparator.comparing(Student::getName,Comparator.nullsFirst(String::compareTo));
Collections.sort(al,cm1);
System.out.println("Considers null to be less than non-null");
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
Comparator<Student> cm2=Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo));
Collections.sort(al,cm2);
System.out.println("Considers null to be greater than non-null");
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Considers null to be less than non-null
105 null 21
106 Ajay 27
101 Vijay 23
Considers null to be greater than non-null
106 Ajay 27
101 Vijay 23
105 null 21
Difference between Comparable and Comparator
Comparable and Comparator both are interfaces and can be used to sort collection elements.
However, there are many differences between Comparable and Comparator interfaces that are given below.
Comparable | Comparator |
1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. | The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc. |
2) Comparable affects the original class, i.e., the actual class is modified. | Comparator doesn't affect the original class, i.e., the actual class is not modified. |
3) Comparable provides compareTo() method to sort elements. | Comparator provides compare() method to sort elements. |
4) Comparable is present in java.lang package. | A Comparator is present in the java.util package. |
5) We can sort the list elements of Comparable type by Collections.sort(List) method. | We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method. |
Java Comparable Example
Let's see the example of a Comparable interface that sorts the list elements on the basis of age.
File: TestSort3.java
//Java Program to demonstrate the use of Java Comparable.
//Creating a class which implements Comparable Interface
import java.util.*;
import java.io.*;
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
//Creating a test class to sort the elements
public class TestSort3{
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));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
105 Jai 21 101 Vijay 23 106 Ajay 27
Java Comparator Example
Let's see an example of the Java Comparator interface where we are sorting the elements of a list using different comparators.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
}
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;
}
}
This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.
import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
}
}
In this class, we are printing the values of the object by sorting on the basis of name and age.
//Java Program to demonstrate the use of Java Comparator
import java.util.*;
import java.io.*;
class TestComparator{
public static void main(String args[]){
//Creating a list of students
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");
//Using NameComparator to sort the elements
Collections.sort(al,new NameComparator());
//Traversing the elements of list
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by Age");
//Using AgeComparator to sort the elements
Collections.sort(al,new AgeComparator());
//Travering the list again
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by Age
105 Jai 21
101 Vijay 23
106 Ajay 27
Properties class in Java
The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system.
An Advantage of the properties file
Recompilation is not required if the information is changed from a properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently.
Constructors of Properties class
Method | Description |
Properties() | It creates an empty property list with no default values. |
Properties(Properties defaults) | It creates an empty property list with the specified defaults. |
Methods of Properties class
The commonly used methods of Properties class are given below.
Method | Description |
public void load(Reader r) | It loads data from the Reader object. |
public void load(InputStream is) | It loads data from the InputStream object |
public void loadFromXML(InputStream in) | It is used to load all of the properties represented by the XML document on the specified input stream into this properties table. |
public String getProperty(String key) | It returns value based on the key. |
public String getProperty(String key, String defaultValue) | It searches for the property with the specified key. |
public void setProperty(String key, String value) | It calls the put method of Hashtable. |
public void list(PrintStream out) | It is used to print the property list out to the specified output stream. |
public void list(PrintWriter out)) | It is used to print the property list out to the specified output stream. |
public Enumeration<?> propertyNames()) | It returns an enumeration of all the keys from the property list. |
public Set<String> stringPropertyNames() | It returns a set of keys in from property list where the key and its corresponding value are strings. |
public void store(Writer w, String comment) | It writes the properties in the writer object. |
public void store(OutputStream os, String comment) | It writes the properties in the OutputStream object. |
public void storeToXML(OutputStream os, String comment) | It writes the properties in the writer object for generating XML document. |
public void storeToXML(Writer w, String comment, String encoding) | It writes the properties in the writer object for generating XML document with the specified encoding. |
Example of Properties class to get information from the properties file
To get information from the properties file, create the properties file first.
user=system
password=oracle
Now, let's create the java class to read the data from the properties file.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:system
oracle
Now if you change the value of the properties file, you don't need to recompile the java class. That means no maintenance problem.
Example of Properties class to get all the system properties
By System.getProperties() method we can get all the properties of the system. Let's create the class that gets information from the system properties.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
Example of Properties class to create the properties file
Now let's write the code to create the properties file.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
Properties p=new Properties();
p.setProperty("name","Sonoo Jaiswal");
p.setProperty("email","sonoojaiswal@javatpoint.com");
p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");
}
}
Let's see the generated properties file.
#Javatpoint Properties Example
#Thu Oct 03 22:35:53 IST 2013
name=Sonoo Jaiswal
Difference between ArrayList and Vector
ArrayList and Vector both implements List interface and maintains insertion order.
However, there are many differences between ArrayList and Vector classes that are given below.
| ArrayList | Vector | | --- | --- | | 1) ArrayList is not synchronized. | Vector is synchronized. | | 2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity. | Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity. | | 3) ArrayList is not a legacy class. It is introduced in JDK 1.2. | Vector is a legacy class. | | 4) ArrayList is fast because it is non-synchronized. | Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object. | | 5) ArrayList uses the Iterator interface to traverse the elements. | A Vector can use the Iterator interface or Enumeration interface to traverse the elements. |
Example of Java ArrayList
Let's see a simple example where we are using ArrayList to store and traverse the elements.
import java.util.*;
class TestArrayList21{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
al.add("James");
al.add("Andy");
//traversing elements using Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Sonoo Michael James Andy
Example of Java Vector
Let's see a simple example of a Java Vector class that uses the Enumeration interface.
import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Output:
umesh
irfan
kumar
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case.
The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws the ConcurrentModificationException.
It is similar to the ArrayList, but with two differences-
Vector is synchronized.
Java Vector contains many legacy methods that are not the part of a collections framework.
Java Vector class Declaration
public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable
Java Vector Constructors
Vector class supports four types of constructors. These are given below:
SN | Constructor | Description |
1) | vector() | It constructs an empty vector with the default size as 10. |
2) | vector(int initialCapacity) | It constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. |
3) | vector(int initialCapacity, int capacityIncrement) | It constructs an empty vector with the specified initial capacity and capacity increment. |
4) | Vector( Collection<? extends E> c) | It constructs a vector that contains the elements of a collection c. |
Java Vector Methods
The following are the list of Vector class methods:
SN | Method | Description |
1) | add() | It is used to append the specified element in the given vector. |
2) | addAll() | It is used to append all of the elements in the specified collection to the end of this Vector. |
3) | addElement() | It is used to append the specified component to the end of this vector. It increases the vector size by one. |
4) | capacity() | It is used to get the current capacity of this vector. |
5) | clear() | It is used to delete all of the elements from this vector. |
6) | clone() | It returns a clone of this vector. |
7) | contains() | It returns true if the vector contains the specified element. |
8) | containsAll() | It returns true if the vector contains all of the elements in the specified collection. |
9) | copyInto() | It is used to copy the components of the vector into the specified array. |
10) | elementAt() | It is used to get the component at the specified index. |
11) | elements() | It returns an enumeration of the components of a vector. |
12) | ensureCapacity() | It is used to increase the capacity of the vector which is in use, if necessary. It ensures that the vector can hold at least the number of components specified by the minimum capacity argument. |
13) | equals() | It is used to compare the specified object with the vector for equality. |
14) | firstElement() | It is used to get the first component of the vector. |
15) | forEach() | It is used to perform the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
16) | get() | It is used to get an element at the specified position in the vector. |
17) | hashCode() | It is used to get the hash code value of a vector. |
18) | indexOf() | It is used to get the index of the first occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element. |
19) | insertElementAt() | It is used to insert the specified object as a component in the given vector at the specified index. |
20) | isEmpty() | It is used to check if this vector has no components. |
21) | iterator() | It is used to get an iterator over the elements in the list in proper sequence. |
22) | lastElement() | It is used to get the last component of the vector. |
23) | lastIndexOf() | It is used to get the index of the last occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element. |
24) | listIterator() | It is used to get a list iterator over the elements in the list in proper sequence. |
25) | remove() | It is used to remove the specified element from the vector. If the vector does not contain the element, it is unchanged. |
26) | removeAll() | It is used to delete all the elements from the vector that are present in the specified collection. |
27) | removeAllElements() | It is used to remove all elements from the vector and set the size of the vector to zero. |
28) | removeElement() | It is used to remove the first (lowest-indexed) occurrence of the argument from the vector. |
29) | removeElementAt() | It is used to delete the component at the specified index. |
30) | removeIf() | It is used to remove all of the elements of the collection that satisfy the given predicate. |
31) | removeRange() | It is used to delete all of the elements from the vector whose index is between fromIndex, inclusive and toIndex, exclusive. |
32) | replaceAll() | It is used to replace each element of the list with the result of applying the operator to that element. |
33) | retainAll() | It is used to retain only that element in the vector which is contained in the specified collection. |
34) | set() | It is used to replace the element at the specified position in the vector with the specified element. |
35) | setElementAt() | It is used to set the component at the specified index of the vector to the specified object. |
36) | setSize() | It is used to set the size of the given vector. |
37) | size() | It is used to get the number of components in the given vector. |
38) | sort() | It is used to sort the list according to the order induced by the specified Comparator. |
39) | spliterator() | It is used to create a late-binding and fail-fast Spliterator over the elements in the list. |
40) | subList() | It is used to get a view of the portion of the list between fromIndex, inclusive, and toIndex, exclusive. |
41) | toArray() | It is used to get an array containing all of the elements in this vector in correct order. |
42) | toString() | It is used to get a string representation of the vector. |
43) | trimToSize() | It is used to trim the capacity of the vector to the vector's current size. |
Java Vector Example
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+vec);
}
}
Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Java Vector Example 2
import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
Java Vector Example 3
import java.util.*;
public class VectorExample2 {
public static void main(String args[]) {
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);
//Display the vector elements
System.out.println("Values in vector: " +in);
//use remove() method to delete the first occurence of an element
System.out.println("Remove first occourence of element 200: "+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " +in);
//Remove the element at index 4
System.out.println("Remove element at index 4: " +in.remove(4));
System.out.println("New Value list in vector: " +in);
//Remove an element
in.removeElementAt(5);
//Checking vector and displays the element
System.out.println("Vector element after removal: " +in);
//Get the hashcode for this vector
System.out.println("Hash code of this vector = "+in.hashCode());
//Get the element at specified index
System.out.println("Element at index 1 is = "+in.get(1));
}
}
Output:
Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300
Java Deque
A deque is a linear collection that supports insertion and deletion of elements from both the ends. The name 'deque' is an abbreviation for double-ended queue.
There are no fixed limits on the deque for the number of elements they may contain. However, this interface supports capacity restricted deques as well as the deques with no fixed size limits. There are various methods which are provided to insert, remove and examine the elements.
These methods typically exist in two forms: the one that throws an exception when the particular operation fails and the other returns a special value which can be either null or false depending upon the operations.
Methods
The java.util.Deque interface provides methods to perform the operations of double-ended queue in Java. Its implementation class is java.util.ArrayDeque.
Methods | Description |
add(E e) | This method is used to insert a specified element into the queue represented by the deque |
addAll(Collection<? Extends E>c) | Adds all the elements in the specified collection at the end of the deque. |
addFirst(E e) | Inserts the specified element at the front of the deque. |
addLast(E e) | Inserts the specified element at the end of the deque. |
contains(object o) | Returns true if the deque contains the specified element. |
descendingIterator() | Returns an iterator over the elements in reverse sequential order. |
element() | Retrieves the head of the queue represented by the deque. |
getFirst() | Retrieves but does not remove the first element of the deque. |
getLast() | Retrieves but does not remove the last element of the deque. |
iterator() | Returns an iterator over the element in the deque in a proper sequence. |
offer(E e) | Inserts the specified element into the deque, returning true upon success and false if no space is available. |
offerFirst() | Inserts the specified element at the front of the deque unless it violates the capacity restriction. |
offerLast() | Inserts the specified element at the end of the deque unless it violates the capacity restriction. |
peek() | Retrieves but does not move the head of the queue represented by the deque or may return null if the deque is empty. |
peekFirst() | Retrieves but does not move the first element of the deque or may return null if the deque is empty. |
peekLast() | Retrieves but does not move the last element of the deque or may return null if the deque is empty. |
poll() | Retrieves and remove the head of the queue represented by the deque or may return null if the deque is empty. |
pollFirst() | Retrieves and remove the first element of the deque or may return null if the deque is empty. |
pollLast() | Retrieves and remove the last element of the deque or may return null if the deque is empty. |
pop() | Pops an element from the stack represented by the deque. |
push() | Pushes an element onto the stack represented by the deque. |
remove() | Retrieves and remove the head of the queue represented by the deque. |
remove(Object o) | Removes the first occurrence of the specified element from the deque. |
removeFirst() | Retrieves and remove the first element from the deque. |
removeFirstOccurrence(Object o) | Remove the first occurrence of the element from the deque. |
removeLast() | Retrieve and remove the last element from the deque. |
removeLastOccurrence(Object o) | Remove the last occurrence of the element from the deque. |
size() | Returns the total number of elements in the deque. |
Example 1
import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeExample1 {
public static void main(String[] args) {
Deque<Integer> deque = new ArrayDeque<Integer>();
// Inserts the element.
deque.add(1);
deque.add(2);
deque.add(3);
System.out.println("Inserting three elements : ");
for (Integer integer : deque) {
System.out.println(integer);
}
// Popping the element.
deque.pop();
System.out.println("After popping : ");
for (Integer integer : deque) {
System.out.println(integer);
}
deque.remove(3);
System.out.println("Removing the element 3 :"+deque);
}
}
Output:
Inserting three elements :
1
2
3
After popping :
2
3
Removing the element 3 :[2]
Example 2
import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeExample2 {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<String>();
// Adding the element in the front of the deque.
deque.addFirst("Java");
System.out.println("The first element is : "+deque);
// Again adding the element in the front of the deque.
deque.addFirst("Python");
System.out.println("After adding the next element in the front of the deque : "+deque);
deque.add("Ruby");
System.out.println("The final deque is : "+deque);
// Returns the number of elements.
int size = deque.size();
System.out.println("The number of elements are : "+size);
// Removes the last element.
deque.removeLast();
System.out.println("Deque after removing the last element is given as : "+deque);
}
}
Output:
The first element is : [Java]
After adding the next element in the front of the deque : [Python, Java]
The final deque is : [Python, Java, Ruby]
The number of elements are : 3
Deque after removing the last element is given as : [Python, Java]
Java ConcurrentHashMap class
A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details..
Java ConcurrentHashMap class declaration
public class ConcurrentHashMap<K,V>
extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable
List of ConcurrentHashMap class Methods
NO | Method | Description |
1. | public void clear() | The clear() method of ConcurrentHashMap class removes all of the mappings from this map. |
2. | public V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | The compute() method of ConcurrentHashMap class Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
3. | public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | The computeIfAbsent() method of ConcurrentHashMap class attempts to compute its value using the given mapping function and enters it into this map unless null If the specified key is not already associated with a value. |
4. | public V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | The computeIfPresent() method of ConcurrentHashMap class Attempts to compute a new mapping given the key and its current mapped value, If the value for the specified key is present. |
5. | public boolean contains(Object value) | The contains() method of ConcurrentHashMap class tests if some key maps into the specified value in this table.. |
6. | public boolean containsKey(Object key) | The containsKey() method of ConcurrentHashMap class tests if the specified object is a key in this table. |
7. | public boolean containsValue(Object value) | The containsValue() method of ConcurrentHashMap class returns true if this map maps one or more keys to the specified value. Note: This method may require a full traversal of the map, and is much slower than method containsKey. |
8. | public Enumeration<V> elements() | The elements() method of ConcurrentHashMap class returns an enumeration of the values in this table. |
9. | public Set<Map.Entry<K,V>> entrySet() | The entrySet() method of ConcurrentHashMap class Returns a Set view of the mappings contained in this map. The changes made to the map are reflected in the set, and vice-versa. |
10. | public boolean equals(Object o) | The elements() method of ConcurrentHashMap class Compares the specified object with this map for equality and returns true if the given object is a map with the same mappings as this map. |
11. | public V get(Object key) | The get() method of ConcurrentHashMap class Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
12. | public V getOrDefault(Object key, V defaultValue) | The getOrDefault() method of ConcurrentHashMap class Returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key. |
13. | public int hashCode() | The hashcode() method of ConcurrentHashMap class Returns the hash code value for this Map, i.e., the sum of, for each key-value pair in the map, key.hashCode() ^ value.hashCode(). |
14. | public Enumeration<K> keys() | The keys() method of ConcurrentHashMap class returns an enumeration of the keys in this table. |
15. | public ConcurrentHashMap.KeySetView<K,V> keySet() | |
public ConcurrentHashMap.KeySetView<K,V> keySet(V mappedValue) | The keySet() method of ConcurrentHashMap class returns a Set view of the keys contained in this map. The set is stacked by the map, so changes to the map are reflected in the set, and vice-versa. | |
16. | public long mappingCount() | The mappingCount() method of ConcurrentHashMap class returns the number of mappings. The value returned is an estimated value; the actual count may differ if there are concurrent insertions or removals. |
17. | public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | The merge() method of ConcurrentHashMap class merge sets If the specified key is not already associated with a (non-null) value, associates it with the given value. |
18. | public static <K> ConcurrentHashMap.KeySetView<K,Boolean> newKeySet() | |
public static <K> ConcurrentHashMap.KeySetView<K,Boolean> newKeySet(int initialCapacity) | The newKeySet() method of ConcurrentHashMap class Creates a new Set backed by a ConcurrentHashMap from the given type to Boolean.TRUE. | |
19. | public V put(K key, V value) | The put() method of ConcurrentHashMap class Maps the specified key to the specified value in this table. |
20. | public void putAll(Map<? extends K,? extends V> m) | The putAll() method of ConcurrentHashMap class Copies all of the mappings from the specified map to this one. These mappings replace any mappings that this map had for any of the keys currently in the specified map. |
21. | public V putIfAbsent(K key, V value) | The putIfAbsent() method of ConcurrentHashMap class Maps If the specified key is not already associated with a value, associates it with the given value. This is equivalent to, for this map. |
22. | public V remove(Object key) | |
public boolean remove(Object key, Object value) | The remove() method of ConcurrentHashMap class Removes the key (and its corresponding value) from this map. This method does nothing if the key is not on the map. | |
23. | public V replace(K key, V value) | |
public boolean replace(K key, V oldValue, V newValue) | The replace() method of ConcurrentHashMap class replaces the entry for a key only if currently mapped to some value. This is equivalent to, for this map. | |
24. | public String toString() | The toString() method of ConcurrentHashMap class returns a string representation of this map. The string representation consists of a list of key-value mappings (in no particular order) enclosed in braces ("{}"). |
25. | public void forEach(long parallelismThreshold, BiConsumer<? super K,? super V> action) | |
public <U> void forEach(long parallelismThreshold, BiFunction<? super K,? super V,? extends U> transformer, Consumer<? super U> action) | The forEach() method of ConcurrentHashMap class Performs the given action for each (key, value). | |
26. | public Collection<V> values() | The values() method of ConcurrentHashMap class returns a Collection view of the values contained in this map. The map backs the collection, so changes to the map are reflected in the collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from this map, via the Iterator |
Java ConcurrentHashMap class Example: computeIfAbsent()
//import statement
import java.util.concurrent.*;
import java.util.*;
public class ConcurrentHashMapcomputeIfAbsentExample1_1 {
public static void main(String[] args)
{
// crete a HashMap and add some values
HashMap<String, Integer> mapcon
\= new HashMap<>();
mapcon.put("k1", 100);
mapcon.put("k2", 200);
mapcon.put("k3", 300);
mapcon.put("k4", 400);
System.out.println("HashMap values :\n " + mapcon.toString());
mapcon.computeIfAbsent("k5", k -> 200 + 300);
mapcon.computeIfAbsent("k6", k -> 60 * 10);
System.out.println("New HashMap after computeIfAbsent :\n "+ mapcon);
}
}
Output:
HashMap values :
{k1=100, k2=200, k3=300, k4=400}
New HashMap after computeIfAbsent :
{k1=100, k2=200, k3=300, k4=400, k5=500, k6=600}
Java ConcurrentHashMap Class Example: containsValue()
import java.util.*;
import java.util.concurrent.*;
public class ConcurrentHashMapcontainsValueExample1_1 {
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> mymap = new ConcurrentHashMap<String, Integer>();
mymap.put("AAA", 10);
mymap.put("BBB", 15);
mymap.put("CCC", 25);
mymap.put("DDD", 255);
mymap.put("EEE",30);
System.out.println(" Mappings are: " +mymap);
System.out.println("is 255 present? :: "
- mymap.containsValue(255));
}
}
Output:
Mappings are: {AAA=10, CCC=25, BBB=15, EEE=30, DDD=255}
is 255 present? :: true
Java ConcurrentLinkedQueue Class
ConcurrentLinkedQueue is an unbounded thread-safe queue which arranges the element in FIFO. New elements are added at the tail of this queue and the elements are added from the head of this queue.
ConcurrentLinkedQueue class and its iterator implements all the optional methods of the Queue and Iterator interfaces.
Methods
Methods | Description |
add() | Inserts the specified element at the tail of this queue |
addAll() | Inserts all the elements which are present in the specified collection to the tail of this queue |
contains() | Returns true if this queue contains the specified element |
forEach() | Performs the given action for each element until all elements have been processed. |
isEmpty() | Returns true if this queue contains no elements. |
iterator() | Returns an iterator over the elements in this queue |
offer() | Inserts the specified element at the tail of this queue |
remove() | Removes the specified element from this queue, if this element is present in the queue |
removeAll() | Removes all the elements of this in queue which are present in the specified collection. |
removeIf() | Removes all the elements in this queue that satisfy the given predicate filter. |
retainAll() | Retain only those elements in this queue that are present in the specified collection. |
size() | Returns the number of the elements in this queue. |
spliterator() | Returns a spliterator over the elements in this queue. |
toArray() | Returns an array containing all the elements of this queue which are in proper sequence. |
Example 1
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaConcurrentLinkedQueueExample1 {
public static void main(String[] args) {
int j =1;
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
for (int i = 1; i <=5; i++) {
// Adding items to the tail of this queue
queue.add(i);}
//inserts the element at the tail of this queue
queue.offer(6);
System.out.println("Queue : "+queue);
//Returns true if this queue contains the specified element
if(queue.contains(4)){
System.out.println("This queue conatins 4");
}
else{
System.out.println("4 is absent");
}
//returns true if the queue is empty
if(queue.isEmpty()){
System.out.println("Add some elements because the queue is empty.");
}
else{
System.out.println("Queue is not empty");
}
}
}
Output:
Queue : [1, 2, 3, 4, 5, 6]
This queue conatins 4
Queue is not empty
Example 2
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaConcurrentLinkedQueueExample2 {
public static void main(String[] args) {
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
List<Integer> list = new ArrayList<Integer>();
queue.add(11);
queue.add(100);
queue.add(122);
queue.add(102);
queue.add(112);
list.add(11);
list.add(100);
System.out.println("Elements in queue : "+queue);
//remove() method will remove the specified element from the queue
queue.remove(122);
queue.remove(102);
System.out.println("Remaining elements in queue : "+queue);
//Removes all the elements of this in queue which are present in the list
queue.removeAll(list);
System.out.println("Elemts of the list will get removed : "+queue);
//Retain only those elements in this queue that are present in the list
queue.retainAll(list);
System.out.println("Queue will retain the elements of the list: "+queue);
}
}
Output:
Elements in queue : [11, 100, 122, 102, 112]
Remaining elements in queue : [11, 100, 112]
Elemts of the list will get removed : [112]
Queue will retain the elements of the list: []
Java ConcurrentHashMap class
A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details..
Java ConcurrentHashMap class declaration
public class ConcurrentHashMap<K,V>
extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable
List of ConcurrentHashMap class Methods
NO | Method | Description |
1. | public void clear() | The clear() method of ConcurrentHashMap class removes all of the mappings from this map. |
2. | public V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | The compute() method of ConcurrentHashMap class Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
3. | public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | The computeIfAbsent() method of ConcurrentHashMap class attempts to compute its value using the given mapping function and enters it into this map unless null If the specified key is not already associated with a value. |
4. | public V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | The computeIfPresent() method of ConcurrentHashMap class Attempts to compute a new mapping given the key and its current mapped value, If the value for the specified key is present. |
5. | public boolean contains(Object value) | The contains() method of ConcurrentHashMap class tests if some key maps into the specified value in this table.. |
6. | public boolean containsKey(Object key) | The containsKey() method of ConcurrentHashMap class tests if the specified object is a key in this table. |
7. | public boolean containsValue(Object value) | The containsValue() method of ConcurrentHashMap class returns true if this map maps one or more keys to the specified value. Note: This method may require a full traversal of the map, and is much slower than method containsKey. |
8. | public Enumeration<V> elements() | The elements() method of ConcurrentHashMap class returns an enumeration of the values in this table. |
9. | public Set<Map.Entry<K,V>> entrySet() | The entrySet() method of ConcurrentHashMap class Returns a Set view of the mappings contained in this map. The changes made to the map are reflected in the set, and vice-versa. |
10. | public boolean equals(Object o) | The elements() method of ConcurrentHashMap class Compares the specified object with this map for equality and returns true if the given object is a map with the same mappings as this map. |
11. | public V get(Object key) | The get() method of ConcurrentHashMap class Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
12. | public V getOrDefault(Object key, V defaultValue) | The getOrDefault() method of ConcurrentHashMap class Returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key. |
13. | public int hashCode() | The hashcode() method of ConcurrentHashMap class Returns the hash code value for this Map, i.e., the sum of, for each key-value pair in the map, key.hashCode() ^ value.hashCode(). |
14. | public Enumeration<K> keys() | The keys() method of ConcurrentHashMap class returns an enumeration of the keys in this table. |
15. | public ConcurrentHashMap.KeySetView<K,V> keySet() | |
public ConcurrentHashMap.KeySetView<K,V> keySet(V mappedValue) | The keySet() method of ConcurrentHashMap class returns a Set view of the keys contained in this map. The set is stacked by the map, so changes to the map are reflected in the set, and vice-versa. | |
16. | public long mappingCount() | The mappingCount() method of ConcurrentHashMap class returns the number of mappings. The value returned is an estimated value; the actual count may differ if there are concurrent insertions or removals. |
17. | public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | The merge() method of ConcurrentHashMap class merge sets If the specified key is not already associated with a (non-null) value, associates it with the given value. |
18. | public static <K> ConcurrentHashMap.KeySetView<K,Boolean> newKeySet() | |
public static <K> ConcurrentHashMap.KeySetView<K,Boolean> newKeySet(int initialCapacity) | The newKeySet() method of ConcurrentHashMap class Creates a new Set backed by a ConcurrentHashMap from the given type to Boolean.TRUE. | |
19. | public V put(K key, V value) | The put() method of ConcurrentHashMap class Maps the specified key to the specified value in this table. |
20. | public void putAll(Map<? extends K,? extends V> m) | The putAll() method of ConcurrentHashMap class Copies all of the mappings from the specified map to this one. These mappings replace any mappings that this map had for any of the keys currently in the specified map. |
21. | public V putIfAbsent(K key, V value) | The putIfAbsent() method of ConcurrentHashMap class Maps If the specified key is not already associated with a value, associates it with the given value. This is equivalent to, for this map. |
22. | public V remove(Object key) | |
public boolean remove(Object key, Object value) | The remove() method of ConcurrentHashMap class Removes the key (and its corresponding value) from this map. This method does nothing if the key is not on the map. | |
23. | public V replace(K key, V value) | |
public boolean replace(K key, V oldValue, V newValue) | The replace() method of ConcurrentHashMap class replaces the entry for a key only if currently mapped to some value. This is equivalent to, for this map. | |
24. | public String toString() | The toString() method of ConcurrentHashMap class returns a string representation of this map. The string representation consists of a list of key-value mappings (in no particular order) enclosed in braces ("{}"). |
25. | public void forEach(long parallelismThreshold, BiConsumer<? super K,? super V> action) | |
public <U> void forEach(long parallelismThreshold, BiFunction<? super K,? super V,? extends U> transformer, Consumer<? super U> action) | The forEach() method of ConcurrentHashMap class Performs the given action for each (key, value). | |
26. | public Collection<V> values() | The values() method of ConcurrentHashMap class returns a Collection view of the values contained in this map. The map backs the collection, so changes to the map are reflected in the collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from this map, via the Iterator |
Java ConcurrentHashMap class Example: computeIfAbsent()
//import statement
import java.util.concurrent.*;
import java.util.*;
public class ConcurrentHashMapcomputeIfAbsentExample1_1 {
public static void main(String[] args)
{
// crete a HashMap and add some values
HashMap<String, Integer> mapcon
\= new HashMap<>();
mapcon.put("k1", 100);
mapcon.put("k2", 200);
mapcon.put("k3", 300);
mapcon.put("k4", 400);
System.out.println("HashMap values :\n " + mapcon.toString());
mapcon.computeIfAbsent("k5", k -> 200 + 300);
mapcon.computeIfAbsent("k6", k -> 60 * 10);
System.out.println("New HashMap after computeIfAbsent :\n "+ mapcon);
}
}
Output:
HashMap values :
{k1=100, k2=200, k3=300, k4=400}
New HashMap after computeIfAbsent :
{k1=100, k2=200, k3=300, k4=400, k5=500, k6=600}
Java ConcurrentHashMap Class Example: containsValue()
import java.util.*;
import java.util.concurrent.*;
public class ConcurrentHashMapcontainsValueExample1_1 {
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> mymap = new ConcurrentHashMap<String, Integer>();
mymap.put("AAA", 10);
mymap.put("BBB", 15);
mymap.put("CCC", 25);
mymap.put("DDD", 255);
mymap.put("EEE",30);
System.out.println(" Mappings are: " +mymap);
System.out.println("is 255 present? :: "
- mymap.containsValue(255));
}
}
Output:
Mappings are: {AAA=10, CCC=25, BBB=15, EEE=30, DDD=255}
is 255 present? :: true