Java Map Interface

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

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:

Java Map Hierarchy

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.

ClassDescription
HashMapHashMap is the implementation of Map, but it doesn't maintain any order.
LinkedHashMapLinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.
TreeMapTreeMap is the implementation of Map and SortedMap. It maintains ascending order.

Useful methods of Map interface

MethodDescription
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

MethodDescription
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)

  1. //Non-generic

  2. import  java.util.*;

  3. public class  MapExample1 {

  4. public static void  main(String[] args) {

  5. Map map=new  HashMap();

  6. //Adding elements to map

  7. map.put(1,"Amit");

  8. map.put(5,"Rahul");

  9. map.put(2,"Jai");

  10. map.put(6,"Amit");

  11. //Traversing Map

  12. Set set=map.entrySet();//Converting to Set so that we can traverse

  13. Iterator itr=set.iterator();

  14. while(itr.hasNext()){

  15. //Converting to Map.Entry so that we can get key and value separately

  16. Map.Entry entry=(Map.Entry)itr.next();

  17. System.out.println(entry.getKey()+" "+entry.getValue());

  18. }

  19. }

  20. }

Output:

1 Amit
2 Jai
5 Rahul
6 Amit

Java Map Example: Generic (New Style)

  1. import  java.util.*;

  2. class  MapExample2{

  3. public static void  main(String args[]){

  4. Map<Integer,String> map=new  HashMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. //Elements can traverse in any order

  9. for(Map.Entry m:map.entrySet()){

  10. System.out.println(m.getKey()+" "+m.getValue());

  11. }

  12. }

  13. }

Output:

102 Rahul
100 Amit
101 Vijay

Java Map Example: comparingByKey()

  1. import  java.util.*;

  2. class  MapExample3{

  3. public static void  main(String args[]){

  4. Map<Integer,String> map=new  HashMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. //Returns a Set view of the mappings contained in this map

  9. map.entrySet()

  10. //Returns a sequential Stream with this collection as its source

  11. .stream()

  12. //Sorted according to the provided Comparator

  13. .sorted(Map.Entry.comparingByKey())

  14. //Performs an action for each element of this stream

  15. .forEach(System.out::println);

  16. }

  17. }

Output:

100=Amit
101=Vijay
102=Rahul

Java Map Example: comparingByKey() in Descending Order

  1. import  java.util.*;

  2. class  MapExample4{

  3. public static void  main(String args[]){

  4. Map<Integer,String> map=new  HashMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. //Returns a Set view of the mappings contained in this map

  9. map.entrySet()

  10. //Returns a sequential Stream with this collection as its source

  11. .stream()

  12. //Sorted according to the provided Comparator

  13. .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))

  14. //Performs an action for each element of this stream

  15. .forEach(System.out::println);

  16. }

  17. }

Output:

102=Rahul
101=Vijay
100=Amit

Java Map Example: comparingByValue()

  1. import  java.util.*;

  2. class  MapExample5{

  3. public static void  main(String args[]){

  4. Map<Integer,String> map=new  HashMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. //Returns a Set view of the mappings contained in this map

  9. map.entrySet()

  10. //Returns a sequential Stream with this collection as its source

  11. .stream()

  12. //Sorted according to the provided Comparator

  13. .sorted(Map.Entry.comparingByValue())

  14. //Performs an action for each element of this stream

  15. .forEach(System.out::println);

  16. }

  17. }

Output:

100=Amit
102=Rahul
101=Vijay

Java Map Example: comparingByValue() in Descending Order

  1. import  java.util.*;

  2. class  MapExample6{

  3. public static void  main(String args[]){

  4. Map<Integer,String> map=new  HashMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. //Returns a Set view of the mappings contained in this map

  9. map.entrySet()

  10. //Returns a sequential Stream with this collection as its source

  11. .stream()

  12. //Sorted according to the provided Comparator

  13. .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

  14. //Performs an action for each element of this stream

  15. .forEach(System.out::println);

  16. }

  17. }

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.

  1. 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

ConstructorDescription
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

MethodDescription
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.

  1. import java.util.*;

  2. public class HashMapExample1{

  3. public static void main(String args[]){

  4. HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap

  5. map.put(1,"Mango"); //Put elements in Map

  6. map.put(2,"Apple");

  7. map.put(3,"Banana");

  8. map.put(4,"Grapes");

  9. System.out.println("Iterating Hashmap...");

  10. for(Map.Entry m : map.entrySet()){

  11. System.out.println(m.getKey()+" "+m.getValue());

  12. }

  13. }

  14. }

    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.

    1. import java.util.*;

    2. public class HashMapExample2{

    3. public static void main(String args[]){

    4. HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap

    5. map.put(1,"Mango"); //Put elements in Map

    6. map.put(2,"Apple");

    7. map.put(3,"Banana");

    8. map.put(1,"Grapes"); //trying duplicate key

    9. System.out.println("Iterating Hashmap...");

    10. for(Map.Entry m : map.entrySet()){

    11. System.out.println(m.getKey()+" "+m.getValue());

    12. }

    13. }

    14. }

      Iterating Hashmap...
      1 Grapes
      2 Apple
      3 Banana
      

      Java HashMap example to add() elements

      Here, we see different ways to insert elements.

      1. import java.util.*;

      2. class HashMap1{

      3. public static void main(String args[]){

      4. HashMap<Integer,String> hm=new HashMap<Integer,String>();

      5. System.out.println("Initial list of elements: "+hm);

      6. hm.put(100,"Amit");

      7. hm.put(101,"Vijay");

      8. hm.put(102,"Rahul");

      9. System.out.println("After invoking put() method ");

      10. for(Map.Entry m:hm.entrySet()){

      11. System.out.println(m.getKey()+" "+m.getValue());

      12. }

      13. hm.putIfAbsent(103, "Gaurav");

      14. System.out.println("After invoking putIfAbsent() method ");

      15. for(Map.Entry m:hm.entrySet()){

      16. System.out.println(m.getKey()+" "+m.getValue());

      17. }

      18. HashMap<Integer,String> map=new HashMap<Integer,String>();

      19. map.put(104,"Ravi");

      20. map.putAll(hm);

      21. System.out.println("After invoking putAll() method ");

      22. for(Map.Entry m:map.entrySet()){

      23. System.out.println(m.getKey()+" "+m.getValue());

      24. }

      25. }

      26. }

        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.

  1. import java.util.*;

  2. public class HashMap2 {

  3. public static void main(String args[]) {

  4. HashMap<Integer,String> map=new HashMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. map.put(103, "Gaurav");

  9. System.out.println("Initial list of elements: "+map);

  10. //key-based removal

  11. map.remove(100);

  12. System.out.println("Updated list of elements: "+map);

  13. //value-based removal

  14. map.remove(101);

  15. System.out.println("Updated list of elements: "+map);

  16. //key-value pair based removal

  17. map.remove(102, "Rahul");

  18. System.out.println("Updated list of elements: "+map);

  19. }

  20. }

    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.

    1. import java.util.*;

    2. class HashMap3{

    3. public static void main(String args[]){

    4. HashMap<Integer,String> hm=new HashMap<Integer,String>();

    5. hm.put(100,"Amit");

    6. hm.put(101,"Vijay");

    7. hm.put(102,"Rahul");

    8. System.out.println("Initial list of elements:");

    9. for(Map.Entry m:hm.entrySet())

    10. {

    11. System.out.println(m.getKey()+" "+m.getValue());

    12. }

    13. System.out.println("Updated list of elements:");

    14. hm.replace(102, "Gaurav");

    15. for(Map.Entry m:hm.entrySet())

    16. {

    17. System.out.println(m.getKey()+" "+m.getValue());

    18. }

    19. System.out.println("Updated list of elements:");

    20. hm.replace(101, "Vijay", "Ravi");

    21. for(Map.Entry m:hm.entrySet())

    22. {

    23. System.out.println(m.getKey()+" "+m.getValue());

    24. }

    25. System.out.println("Updated list of elements:");

    26. hm.replaceAll((k,v) -> "Ajay");

    27. for(Map.Entry m:hm.entrySet())

    28. {

    29. System.out.println(m.getKey()+" "+m.getValue());

    30. }

    31. }

    32. }

            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

  1. import java.util.*;

  2. class Book {

  3. int id;

  4. String name,author,publisher;

  5. int quantity;

  6. public Book(int id, String name, String author, String publisher, int quantity) {

  7. this.id = id;

  8. this.name = name;

  9. this.author = author;

  10. this.publisher = publisher;

  11. this.quantity = quantity;

  12. }

  13. }

  14. public class MapExample {

  15. public static void main(String[] args) {

  16. //Creating map of Books

  17. Map<Integer,Book> map=new HashMap<Integer,Book>();

  18. //Creating Books

  19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

  20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

  21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

  22. //Adding Books to map

  23. map.put(1,b1);

  24. map.put(2,b2);

  25. map.put(3,b3);

  26. //Traversing map

  27. for(Map.Entry<Integer, Book> entry:map.entrySet()){

  28. int key=entry.getKey();

  29. Book b=entry.getValue();

  30. System.out.println(key+" Details:");

  31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

  32. }

  33. }

  34. }

    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.

    Working of HashMap in Java

    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.

      Working of HashMap in Java

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.

  1. HashMap<String, Integer> map = new HashMap<>();

  2. map.put("Aman", 19);

  3. map.put("Sunny", 29);

  4. 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:

  1. Index = hashcode(Key) & (n-1)

Where n is the size of the array. Hence the index value for "Aman" is:

  1. Index = 2657860 & (16-1) = 4

The value 4 is the computed index value where the Key and value will store in HashMap.

Working of HashMap in Java

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.

  1. 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.

Working of HashMap in Java

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.

  1. HashMap<String, Integer> map = new HashMap<>();

  2. map.put("Aman", 19);

  3. map.put("Sunny", 29);

  4. 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:

  1. Index = hashcode(Key) & (n-1)

Where n is the size of the array. Hence the index value for "Aman" is:

  1. Index = 2657860 & (16-1) = 4

The value 4 is the computed index value where the Key and value will store in HashMap.

Working of HashMap in Java

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.

  1. 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

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.

  1. 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 hierarchy

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.

  1. 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

ConstructorDescription
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

MethodDescription
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

  1. import java.util.*;

  2. class LinkedHashMap1{

  3. public static void main(String args[]){

  4. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();

  5. hm.put(100,"Amit");

  6. hm.put(101,"Vijay");

  7. hm.put(102,"Rahul");

  8. for(Map.Entry m:hm.entrySet()){

  9. System.out.println(m.getKey()+" "+m.getValue());

  10. }

  11. }

  12. }

Output:100 Amit
       101 Vijay
       102 Rahul

Java LinkedHashMap Example: Key-Value pair

  1. import java.util.*;

  2. class LinkedHashMap2{

  3. public static void main(String args[]){

  4. LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();

  5. map.put(100,"Amit");

  6. map.put(101,"Vijay");

  7. map.put(102,"Rahul");

  8. //Fetching key

  9. System.out.println("Keys: "+map.keySet());

  10. //Fetching value

  11. System.out.println("Values: "+map.values());

  12. //Fetching key-value pair

  13. System.out.println("Key-Value pairs: "+map.entrySet());

  14. }

  15. }

Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]

Java LinkedHashMap Example:remove()

  1. import java.util.*;

  2. public class LinkedHashMap3 {

  3. public static void main(String args[]) {

  4. Map<Integer,String> map=new LinkedHashMap<Integer,String>();

  5. map.put(101,"Amit");

  6. map.put(102,"Vijay");

  7. map.put(103,"Rahul");

  8. System.out.println("Before invoking remove() method: "+map);

  9. map.remove(102);

  10. System.out.println("After invoking remove() method: "+map);

  11. }

  12. }

Output:
Before invoking remove() method: {101=Amit, 102=Vijay, 103=Rahul} After invoking remove() method: {101=Amit, 103=Rahul}

Java LinkedHashMap Example: Book

  1. import java.util.*;

  2. class Book {

  3. int id;

  4. String name,author,publisher;

  5. int quantity;

  6. public Book(int id, String name, String author, String publisher, int quantity) {

  7. this.id = id;

  8. this.name = name;

  9. this.author = author;

  10. this.publisher = publisher;

  11. this.quantity = quantity;

  12. }

  13. }

  14. public class MapExample {

  15. public static void main(String[] args) {

  16. //Creating map of Books

  17. Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();

  18. //Creating Books

  19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

  20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

  21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

  22. //Adding Books to map

  23. map.put(2,b2);

  24. map.put(1,b1);

  25. map.put(3,b3);

  26. //Traversing map

  27. for(Map.Entry<Integer, Book> entry:map.entrySet()){

  28. int key=entry.getKey();

  29. Book b=entry.getValue();

  30. System.out.println(key+" Details:");

  31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

  32. }

  33. }

  34. }

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 hierarchy

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.

  1. 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

    1. import java.util.*;

    2. class TreeMap1{

    3. public static void main(String args[]){

    4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();

    5. map.put(100,"Amit");

    6. map.put(102,"Ravi");

    7. map.put(101,"Vijay");

    8. map.put(103,"Rahul");

    9. for(Map.Entry m:map.entrySet()){

    10. System.out.println(m.getKey()+" "+m.getValue());

    11. }

    12. }

    13. }

    Output:100 Amit
           101 Vijay
           102 Ravi
           103 Rahul

Java TreeMap Example: remove()

  1. import java.util.*;

  2. public class TreeMap2 {

  3. public static void main(String args[]) {

  4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(102,"Ravi");

  7. map.put(101,"Vijay");

  8. map.put(103,"Rahul");

  9. System.out.println("Before invoking remove() method");

  10. for(Map.Entry m:map.entrySet())

  11. {

  12. System.out.println(m.getKey()+" "+m.getValue());

  13. }

  14. map.remove(102);

  15. System.out.println("After invoking remove() method");

  16. for(Map.Entry m:map.entrySet())

  17. {

  18. System.out.println(m.getKey()+" "+m.getValue());

  19. }

  20. }

  21. }

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

  1. import java.util.*;

  2. class TreeMap3{

  3. public static void main(String args[]){

  4. NavigableMap<Integer,String> map=new TreeMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(102,"Ravi");

  7. map.put(101,"Vijay");

  8. map.put(103,"Rahul");

  9. //Maintains descending order

  10. System.out.println("descendingMap: "+map.descendingMap());

  11. //Returns key-value pairs whose keys are less than or equal to the specified key.

  12. System.out.println("headMap: "+map.headMap(102,true));

  13. //Returns key-value pairs whose keys are greater than or equal to the specified key.

  14. System.out.println("tailMap: "+map.tailMap(102,true));

  15. //Returns key-value pairs exists in between the specified key.

  16. System.out.println("subMap: "+map.subMap(100, false, 102, true));

  17. }

  18. }

    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

  1. import java.util.*;

  2. class TreeMap4{

  3. public static void main(String args[]){

  4. SortedMap<Integer,String> map=new TreeMap<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(102,"Ravi");

  7. map.put(101,"Vijay");

  8. map.put(103,"Rahul");

  9. //Returns key-value pairs whose keys are less than the specified key.

  10. System.out.println("headMap: "+map.headMap(102));

  11. //Returns key-value pairs whose keys are greater than or equal to the specified key.

  12. System.out.println("tailMap: "+map.tailMap(102));

  13. //Returns key-value pairs exists in between the specified key.

  14. System.out.println("subMap: "+map.subMap(100, 102));

  15. }

  16. }

    headMap: {100=Amit, 101=Vijay}
    tailMap: {102=Ravi, 103=Rahul}
    subMap: {100=Amit, 101=Vijay}

What is difference between HashMap and TreeMap?

HashMapTreeMap
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

  1. import java.util.*;

  2. class Book {

  3. int id;

  4. String name,author,publisher;

  5. int quantity;

  6. public Book(int id, String name, String author, String publisher, int quantity) {

  7. this.id = id;

  8. this.name = name;

  9. this.author = author;

  10. this.publisher = publisher;

  11. this.quantity = quantity;

  12. }

  13. }

  14. public class MapExample {

  15. public static void main(String[] args) {

  16. //Creating map of Books

  17. Map<Integer,Book> map=new TreeMap<Integer,Book>();

  18. //Creating Books

  19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

  20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

  21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

  22. //Adding Books to map

  23. map.put(2,b2);

  24. map.put(1,b1);

  25. map.put(3,b3);

  26. //Traversing map

  27. for(Map.Entry<Integer, Book> entry:map.entrySet()){

  28. int key=entry.getKey();

  29. Book b=entry.getValue();

  30. System.out.println(key+" Details:");

  31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

  32. }

  33. }

  34. }

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.

  1. 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

ConstructorDescription
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

MethodDescription
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

  1. import java.util.*;

  2. class Hashtable1{

  3. public static void main(String args[]){

  4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

  5. hm.put(100,"Amit");

  6. hm.put(102,"Ravi");

  7. hm.put(101,"Vijay");

  8. hm.put(103,"Rahul");

  9. for(Map.Entry m:hm.entrySet()){

  10. System.out.println(m.getKey()+" "+m.getValue());

  11. }

  12. }

  13. }

    Output:

    103 Rahul
    102 Ravi
    101 Vijay
    100 Amit
    

    Java Hashtable Example: remove()

    1. import java.util.*;

    2. public class Hashtable2 {

    3. public static void main(String args[]) {

    4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();

    5. map.put(100,"Amit");

    6. map.put(102,"Ravi");

    7. map.put(101,"Vijay");

    8. map.put(103,"Rahul");

    9. System.out.println("Before remove: "+ map);

    10. // Remove value for key 102

    11. map.remove(102);

    12. System.out.println("After remove: "+ map);

    13. }

    14. }

Output:

        Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
        After remove: {103=Rahul, 101=Vijay, 100=Amit}

Java Hashtable Example: getOrDefault()

  1. import java.util.*;

  2. class Hashtable3{

  3. public static void main(String args[]){

  4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(102,"Ravi");

  7. map.put(101,"Vijay");

  8. map.put(103,"Rahul");

  9. //Here, we specify the if and else statement as arguments of the method

  10. System.out.println(map.getOrDefault(101, "Not Found"));

  11. System.out.println(map.getOrDefault(105, "Not Found"));

  12. }

  13. }

Output:

        Vijay
        Not Found

Java Hashtable Example: putIfAbsent()

  1. import java.util.*;

  2. class Hashtable4{

  3. public static void main(String args[]){

  4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();

  5. map.put(100,"Amit");

  6. map.put(102,"Ravi");

  7. map.put(101,"Vijay");

  8. map.put(103,"Rahul");

  9. System.out.println("Initial Map: "+map);

  10. //Inserts, as the specified pair is unique

  11. map.putIfAbsent(104,"Gaurav");

  12. System.out.println("Updated Map: "+map);

  13. //Returns the current value, as the specified pair already exist

  14. map.putIfAbsent(101,"Vijay");

  15. System.out.println("Updated Map: "+map);

  16. }

  17. }

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

  1. import java.util.*;

  2. class Book {

  3. int id;

  4. String name,author,publisher;

  5. int quantity;

  6. public Book(int id, String name, String author, String publisher, int quantity) {

  7. this.id = id;

  8. this.name = name;

  9. this.author = author;

  10. this.publisher = publisher;

  11. this.quantity = quantity;

  12. }

  13. }

  14. public class HashtableExample {

  15. public static void main(String[] args) {

  16. //Creating map of Books

  17. Map<Integer,Book> map=new Hashtable<Integer,Book>();

  18. //Creating Books

  19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

  20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

  21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

  22. //Adding Books to map

  23. map.put(1,b1);

  24. map.put(2,b2);

  25. map.put(3,b3);

  26. //Traversing map

  27. for(Map.Entry<Integer, Book> entry:map.entrySet()){

  28. int key=entry.getKey();

  29. Book b=entry.getValue();

  30. System.out.println(key+" Details:");

  31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

  32. }

  33. }

  34. }

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.

HashMapHashtable
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()

  1. import java.util.*;

  2. enum days {

  3. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

  4. }

  5. public class EnumSetExample {

  6. public static void main(String[] args) {

  7. Set<days> set1 = EnumSet.allOf(days.class);

  8. System.out.println("Week Days:"+set1);

  9. Set<days> set2 = EnumSet.noneOf(days.class);

  10. System.out.println("Week Days:"+set2);

  11. }

  12. }

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.

  1. 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

ConstructorDescription
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

SNMethodDescription
1clear()It is used to clear all the mapping from the map.
2clone()It is used to copy the mapped value of one map to another map.
3containsKey()It is used to check whether a specified key is present in this map or not.
4containsValue()It is used to check whether one or more key is associated with a given value or not.
5entrySet()It is used to create a set of elements contained in the EnumMap.
6equals()It is used to compare two maps for equality.
7get()It is used to get the mapped value of the specified key.
8hashCode()It is used to get the hashcode value of the EnumMap.
9keySet()It is used to get the set view of the keys contained in the map.
10size()It is used to get the size of the EnumMap.
11Values()It is used to create a collection view of the values contained in this map.
12put()It is used to associate the given value with the given key in this EnumMap.
13putAll()It is used to copy all the mappings from one EnumMap to a new EnumMap.
14remove()It is used to remove the mapping for the given key from EnumMap if the given key is present.

Java EnumMap Example

  1. import java.util.*;

  2. public class EnumMapExample {

  3. // create an enum

  4. public enum Days {

  5. Monday, Tuesday, Wednesday, Thursday

  6. };

  7. public static void main(String[] args) {

  8. //create and populate enum map

  9. EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);

  10. map.put(Days.Monday, "1");

  11. map.put(Days.Tuesday, "2");

  12. map.put(Days.Wednesday, "3");

  13. map.put(Days.Thursday, "4");

  14. // print the map

  15. for(Map.Entry m:map.entrySet()){

  16. System.out.println(m.getKey()+" "+m.getValue());

  17. }

  18. }

  19. }

Output:

Monday 1
Tuesday 2
Wednesday 3
Thursday 4

Java EnumMap Example: Book

  1. import java.util.*;

  2. class Book {

  3. int id;

  4. String name,author,publisher;

  5. int quantity;

  6. public Book(int id, String name, String author, String publisher, int quantity) {

  7. this.id = id;

  8. this.name = name;

  9. this.author = author;

  10. this.publisher = publisher;

  11. this.quantity = quantity;

  12. }

  13. }

  14. public class EnumMapExample {

  15. // Creating enum

  16. public enum Key{

  17. One, Two, Three

  18. };

  19. public static void main(String[] args) {

  20. EnumMap<Key, Book> map = new EnumMap<Key, Book>(Key.class);

  21. // Creating Books

  22. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

  23. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

  24. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

  25. // Adding Books to Map

  26. map.put(Key.One, b1);

  27. map.put(Key.Two, b2);

  28. map.put(Key.Three, b3);

  29. // Traversing EnumMap

  30. for(Map.Entry<Key, Book> entry:map.entrySet()){

  31. Book b=entry.getValue();

  32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

  33. }

  34. }

  35. }

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.

  1. public class Collections extends Object
SNModifier & TypeMethodsDescriptions
1)static <T> booleanaddAll()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> intbinarySearch()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> voidcopy()It is used to copy all the elements from one list into another list.
14)static booleandisjoint()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> voidfill()It is used to replace all of the elements of the specified list with the specified elements.
27)static intfrequency()It is used to get the number of elements in the specified collection equal to the specified object.
28)static intindexOfSubList()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 intlastIndexOfSubList()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>> Tmax()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>> Tmin()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> booleanreplaceAll()It is used to replace all occurrences of one specified value in a list with the other specified value.
36)static voidreverse()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 voidrotate()It is used to rotate the elements in the specified list by a given distance.
39)static voidshuffle()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>>voidsort()It is used to sort the elements presents in the specified list of collection in ascending order.
44)static voidswap()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.
60static <T> SortedSet<T>unmodifiableSortedSet()It is used to get an unmodifiable view of the specified sorted set.

Java Collections Example

  1. import java.util.*;

  2. public class CollectionsExample {

  3. public static void main(String a[]){

  4. List<String> list = new ArrayList<String>();

  5. list.add("C");

  6. list.add("Core Java");

  7. list.add("Advance Java");

  8. System.out.println("Initial collection value:"+list);

  9. Collections.addAll(list, "Servlet","JSP");

  10. System.out.println("After adding elements collection value:"+list);

  11. String[] strArr = {"C#", ".Net"};

  12. Collections.addAll(list, strArr);

  13. System.out.println("After adding array collection value:"+list);

  14. }

  15. }

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()

  1. import java.util.*;

  2. public class CollectionsExample {

  3. public static void main(String a[]){

  4. List<Integer> list = new ArrayList<Integer>();

  5. list.add(46);

  6. list.add(67);

  7. list.add(24);

  8. list.add(16);

  9. list.add(8);

  10. list.add(12);

  11. System.out.println("Value of maximum element from the collection: "+Collections.max(list));

  12. }

  13. }

Output:

Value of maximum element from the collection: 67

Java Collections Example: min()

  1. import java.util.*;

  2. public class CollectionsExample {

  3. public static void main(String a[]){

  4. List<Integer> list = new ArrayList<Integer>();

  5. list.add(46);

  6. list.add(67);

  7. list.add(24);

  8. list.add(16);

  9. list.add(8);

  10. list.add(12);

  11. System.out.println("Value of minimum element from the collection: "+Collections.min(list));

  12. }

  13. }

Output:

Value of minimum element from the collection: 8

Sorting in Collection

We can sort the elements of:

  1. String objects

  2. Wrapper class objects

  3. 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

  1. import java.util.*;

  2. class TestSort1{

  3. public static void main(String args[]){

  4. ArrayList<String> al=new ArrayList<String>();

  5. al.add("Viru");

  6. al.add("Saurav");

  7. al.add("Mukesh");

  8. al.add("Tahir");

  9. Collections.sort(al);

  10. Iterator itr=al.iterator();

  11. while(itr.hasNext()){

  12. System.out.println(itr.next());

  13. }

  14. }

  15. }

Test it Now

Mukesh
Saurav
Tahir
Viru

Example to sort string objects in reverse order

  1. import java.util.*;

  2. class TestSort2{

  3. public static void main(String args[]){

  4. ArrayList<String> al=new ArrayList<String>();

  5. al.add("Viru");

  6. al.add("Saurav");

  7. al.add("Mukesh");

  8. al.add("Tahir");

  9. Collections.sort(al,Collections.reverseOrder());

  10. Iterator i=al.iterator();

  11. while(i.hasNext())

  12. {

  13. System.out.println(i.next());

  14. }

  15. }

  16. }

Viru
Tahir
Saurav
Mukesh

Example to sort Wrapper class objects

  1. import java.util.*;

  2. class TestSort3{

  3. public static void main(String args[]){

  4. ArrayList al=new ArrayList();

  5. al.add(Integer.valueOf(201));

  6. al.add(Integer.valueOf(101));

  7. al.add(230);//internally will be converted into objects as Integer.valueOf(230)

  8. Collections.sort(al);

  9. Iterator itr=al.iterator();

  10. while(itr.hasNext()){

  11. System.out.println(itr.next());

  12. }

  13. }

  14. }

101
201
230

Example to sort user-defined class objects

  1. import java.util.*;

  2. class Student implements Comparable<Student> {

  3. public String name;

  4. public Student(String name) {

  5. this.name = name;

  6. }

  7. public int compareTo(Student person) {

  8. return name.compareTo(person.name);

  9. }

  10. }

  11. public class TestSort4 {

  12. public static void main(String[] args) {

  13. ArrayList<Student> al=new ArrayList<Student>();

  14. al.add(new Student("Viru"));

  15. al.add(new Student("Saurav"));

  16. al.add(new Student("Mukesh"));

  17. al.add(new Student("Tahir"));

  18. Collections.sort(al);

  19. for (Student s : al) {

  20. System.out.println(s.name);

  21. }

  22. }

  23. }

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:

  1. String objects

  2. Wrapper class objects

  3. 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:

  1. String objects

  2. Wrapper class objects

  3. 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

  1. class Student implements Comparable<Student>{

  2. int rollno;

  3. String name;

  4. int age;

  5. Student(int rollno,String name,int age){

  6. this.rollno=rollno;

  7. this.name\=name;

  8. this.age=age;

  9. }

  10. public int compareTo(Student st){

  11. if(age==st.age)

  12. return 0;

  13. else if(age>st.age)

  14. return 1;

  15. else

  16. return -1;

  17. }

  18. }

File: TestSort1.java

  1. import java.util.*;

  2. public class TestSort1{

  3. public static void main(String args[]){

  4. ArrayList<Student> al=new ArrayList<Student>();

  5. al.add(new Student(101,"Vijay",23));

  6. al.add(new Student(106,"Ajay",27));

  7. al.add(new Student(105,"Jai",21));

  8. Collections.sort(al);

  9. for(Student st:al){

  10. System.out.println(st.rollno+" "+st.name+" "+st.age);

  11. }

  12. }

  13. }

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

  1. class Student implements Comparable<Student>{

  2. int rollno;

  3. String name;

  4. int age;

  5. Student(int rollno,String name,int age){

  6. this.rollno=rollno;

  7. this.name\=name;

  8. this.age=age;

  9. }

  10. public int compareTo(Student st){

  11. if(age==st.age)

  12. return 0;

  13. else if(age<st.age)

  14. return 1;

  15. else

  16. return -1;

  17. }

  18. }

File: TestSort2.java

  1. import java.util.*;

  2. public class TestSort2{

  3. public static void main(String args[]){

  4. ArrayList<Student> al=new ArrayList<Student>();

  5. al.add(new Student(101,"Vijay",23));

  6. al.add(new Student(106,"Ajay",27));

  7. al.add(new Student(105,"Jai",21));

  8. Collections.sort(al);

  9. for(Student st:al){

  10. System.out.println(st.rollno+" "+st.name+" "+st.age);

  11. }

  12. }

  13. }

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

MethodDescription
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:

  1. Student.java

  2. AgeComparator.java

  3. NameComparator.java

  4. Simple.java

Student.java

This class contains three fields rollno, name and age and a parameterized constructor.

  1. class Student{

  2. int rollno;

  3. String name;

  4. int age;

  5. Student(int rollno,String name,int age){

  6. this.rollno=rollno;

  7. this.name\=name;

  8. this.age=age;

  9. }

  10. }

AgeComparator.java

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.

  1. import java.util.*;

  2. class AgeComparator implements Comparator{

  3. public int compare(Object o1,Object o2){

  4. Student s1=(Student)o1;

  5. Student s2=(Student)o2;

  6. if(s1.age==s2.age)

  7. return 0;

  8. else if(s1.age>s2.age)

  9. return 1;

  10. else

  11. return -1;

  12. }

  13. }

NameComparator.java

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.

  1. import java.util.*;

  2. class NameComparator implements Comparator{

  3. public int compare(Object o1,Object o2){

  4. Student s1=(Student)o1;

  5. Student s2=(Student)o2;

  6. return s1.name.compareTo(s2.name);

  7. }

  8. }

Simple.java

In this class, we are printing the values of the object by sorting on the basis of name and age.

  1. import java.util.*;

  2. import java.io.*;

  3. class Simple{

  4. public static void main(String args[]){

  5. ArrayList al=new ArrayList();

  6. al.add(new Student(101,"Vijay",23));

  7. al.add(new Student(106,"Ajay",27));

  8. al.add(new Student(105,"Jai",21));

  9. System.out.println("Sorting by Name");

  10. Collections.sort(al,new NameComparator());

  11. Iterator itr=al.iterator();

  12. while(itr.hasNext()){

  13. Student st=(Student)itr.next();

  14. System.out.println(st.rollno+" "+st.name+" "+st.age);

  15. }

  16. System.out.println("Sorting by age");

  17. Collections.sort(al,new AgeComparator());

  18. Iterator itr2=al.iterator();

  19. while(itr2.hasNext()){

  20. Student st=(Student)itr2.next();

  21. System.out.println(st.rollno+" "+st.name+" "+st.age);

  22. }

  23. }

  24. }

       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)

Student.java

  1. class Student{

  2. int rollno;

  3. String name;

  4. int age;

  5. Student(int rollno,String name,int age){

  6. this.rollno=rollno;

  7. this.name\=name;

  8. this.age=age;

  9. }

  10. }

AgeComparator.java

  1. import java.util.*;

  2. class AgeComparator implements Comparator<Student>{

  3. public int compare(Student s1,Student s2){

  4. if(s1.age==s2.age)

  5. return 0;

  6. else if(s1.age>s2.age)

  7. return 1;

  8. else

  9. return -1;

  10. }

  11. }

NameComparator.java

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.

  1. import java.util.*;

  2. class NameComparator implements Comparator<Student>{

  3. public int compare(Student s1,Student s2){

  4. return s1.name.compareTo(s2.name);

  5. }

  6. }

Simple.java

In this class, we are printing the values of the object by sorting on the basis of name and age.

  1. import java.util.*;

  2. import java.io.*;

  3. class Simple{

  4. public static void main(String args[]){

  5. ArrayList<Student> al=new ArrayList<Student>();

  6. al.add(new Student(101,"Vijay",23));

  7. al.add(new Student(106,"Ajay",27));

  8. al.add(new Student(105,"Jai",21));

  9. System.out.println("Sorting by Name");

  10. Collections.sort(al,new NameComparator());

  11. for(Student st: al){

  12. System.out.println(st.rollno+" "+st.name+" "+st.age);

  13. }

  14. System.out.println("Sorting by age");

  15. Collections.sort(al,new AgeComparator());

  16. for(Student st: al){

  17. System.out.println(st.rollno+" "+st.name+" "+st.age);

  18. }

  19. }

  20. }

       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

MethodDescription
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

  1. class Student {

  2. int rollno;

  3. String name;

  4. int age;

  5. Student(int rollno,String name,int age){

  6. this.rollno=rollno;

  7. this.name\=name;

  8. this.age=age;

  9. }

  10. public int getRollno() {

  11. return rollno;

  12. }

  13. public void setRollno(int rollno) {

  14. this.rollno = rollno;

  15. }

  16. public String getName() {

  17. return name;

  18. }

  19. public void setName(String name) {

  20. this.name = name;

  21. }

  22. public int getAge() {

  23. return age;

  24. }

  25. public void setAge(int age) {

  26. this.age = age;

  27. }

  28. }

File: TestSort1.java

  1. import java.util.*;

  2. public class TestSort1{

  3. public static void main(String args[]){

  4. ArrayList<Student> al=new ArrayList<Student>();

  5. al.add(new Student(101,"Vijay",23));

  6. al.add(new Student(106,"Ajay",27));

  7. al.add(new Student(105,"Jai",21));

  8. /Sorting elements on the basis of name

  9. Comparator<Student> cm1=Comparator.comparing(Student::getName);

  10. Collections.sort(al,cm1);

  11. System.out.println("Sorting by Name");

  12. for(Student st: al){

  13. System.out.println(st.rollno+" "+st.name+" "+st.age);

  14. }

  15. //Sorting elements on the basis of age

  16. Comparator<Student> cm2=Comparator.comparing(Student::getAge);

  17. Collections.sort(al,cm2);

  18. System.out.println("Sorting by Age");

  19. for(Student st: al){

  20. System.out.println(st.rollno+" "+st.name+" "+st.age);

  21. }

  22. }

  23. }

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

  1. class Student {

  2. int rollno;

  3. String name;

  4. int age;

  5. Student(int rollno,String name,int age){

  6. this.rollno=rollno;

  7. this.name\=name;

  8. this.age=age;

  9. }

  10. public int getRollno() {

  11. return rollno;

  12. }

  13. public void setRollno(int rollno) {

  14. this.rollno = rollno;

  15. }

  16. public String getName() {

  17. return name;

  18. }

  19. public void setName(String name) {

  20. this.name = name;

  21. }

  22. public int getAge() {

  23. return age;

  24. }

  25. public void setAge(int age) {

  26. this.age = age;

  27. }

  28. }

File: TestSort2.java

  1. import java.util.*;

  2. public class TestSort2{

  3. public static void main(String args[]){

  4. ArrayList<Student> al=new ArrayList<Student>();

  5. al.add(new Student(101,"Vijay",23));

  6. al.add(new Student(106,"Ajay",27));

  7. al.add(new Student(105,null,21));

  8. Comparator<Student> cm1=Comparator.comparing(Student::getName,Comparator.nullsFirst(String::compareTo));

  9. Collections.sort(al,cm1);

  10. System.out.println("Considers null to be less than non-null");

  11. for(Student st: al){

  12. System.out.println(st.rollno+" "+st.name+" "+st.age);

  13. }

  14. Comparator<Student> cm2=Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo));

  15. Collections.sort(al,cm2);

  16. System.out.println("Considers null to be greater than non-null");

  17. for(Student st: al){

  18. System.out.println(st.rollno+" "+st.name+" "+st.age);

  19. }

  20. }

  21. }

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.

ComparableComparator
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

  1. //Java Program to demonstrate the use of Java Comparable.

  2. //Creating a class which implements Comparable Interface

  3. import java.util.*;

  4. import java.io.*;

  5. class Student implements Comparable<Student>{

  6. int rollno;

  7. String name;

  8. int age;

  9. Student(int rollno,String name,int age){

  10. this.rollno=rollno;

  11. this.name\=name;

  12. this.age=age;

  13. }

  14. public int compareTo(Student st){

  15. if(age==st.age)

  16. return 0;

  17. else if(age>st.age)

  18. return 1;

  19. else

  20. return -1;

  21. }

  22. }

  23. //Creating a test class to sort the elements

  24. public class TestSort3{

  25. public static void main(String args[]){

  26. ArrayList<Student> al=new ArrayList<Student>();

  27. al.add(new Student(101,"Vijay",23));

  28. al.add(new Student(106,"Ajay",27));

  29. al.add(new Student(105,"Jai",21));

  30. Collections.sort(al);

  31. for(Student st:al){

  32. System.out.println(st.rollno+" "+st.name+" "+st.age);

  33. }

  34. }

  35. }

    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.

    Student.java

    1. class Student{

    2. int rollno;

    3. String name;

    4. int age;

    5. Student(int rollno,String name,int age){

    6. this.rollno=rollno;

    7. this.name\=name;

    8. this.age=age;

    9. }

    10. }

AgeComparator.java

  1. import java.util.*;

  2. class AgeComparator implements Comparator<Student>{

  3. public int compare(Student s1,Student s2){

  4. if(s1.age==s2.age)

  5. return 0;

  6. else if(s1.age>s2.age)

  7. return 1;

  8. else

  9. return -1;

  10. }

  11. }

NameComparator.java

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.

  1. import java.util.*;

  2. class NameComparator implements Comparator<Student>{

  3. public int compare(Student s1,Student s2){

  4. return s1.name.compareTo(s2.name);

  5. }

  6. }

TestComparator.java

In this class, we are printing the values of the object by sorting on the basis of name and age.

  1. //Java Program to demonstrate the use of Java Comparator

  2. import java.util.*;

  3. import java.io.*;

  4. class TestComparator{

  5. public static void main(String args[]){

  6. //Creating a list of students

  7. ArrayList<Student> al=new ArrayList<Student>();

  8. al.add(new Student(101,"Vijay",23));

  9. al.add(new Student(106,"Ajay",27));

  10. al.add(new Student(105,"Jai",21));

  11. System.out.println("Sorting by Name");

  12. //Using NameComparator to sort the elements

  13. Collections.sort(al,new NameComparator());

  14. //Traversing the elements of list

  15. for(Student st: al){

  16. System.out.println(st.rollno+" "+st.name+" "+st.age);

  17. }

  18. System.out.println("sorting by Age");

  19. //Using AgeComparator to sort the elements

  20. Collections.sort(al,new AgeComparator());

  21. //Travering the list again

  22. for(Student st: al){

  23. System.out.println(st.rollno+" "+st.name+" "+st.age);

  24. }

  25. }

  26. }

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

MethodDescription
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.

MethodDescription
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.

db.properties

  1. user=system

  2. password=oracle

Now, let's create the java class to read the data from the properties file.

Test.java

  1. import java.util.*;

  2. import java.io.*;

  3. public class Test {

  4. public static void main(String[] args)throws Exception{

  5. FileReader reader=new FileReader("db.properties");

  6. Properties p=new Properties();

  7. p.load(reader);

  8. System.out.println(p.getProperty("user"));

  9. System.out.println(p.getProperty("password"));

  10. }

  11. }

    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.

Test.java

  1. import java.util.*;

  2. import java.io.*;

  3. public class Test {

  4. public static void main(String[] args)throws Exception{

  5. Properties p=System.getProperties();

  6. Set set=p.entrySet();

  7. Iterator itr=set.iterator();

  8. while(itr.hasNext()){

  9. Map.Entry entry=(Map.Entry)itr.next();

  10. System.out.println(entry.getKey()+" = "+entry.getValue());

  11. }

  12. }

  13. }

    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.

Test.java

  1. import java.util.*;

  2. import java.io.*;

  3. public class Test {

  4. public static void main(String[] args)throws Exception{

  5. Properties p=new Properties();

  6. p.setProperty("name","Sonoo Jaiswal");

  7. p.setProperty("email","sonoojaiswal@javatpoint.com");

  8. p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");

  9. }

  10. }

Let's see the generated properties file.

info.properties

  1. #Javatpoint Properties Example

  2. #Thu Oct 03 22:35:53 IST 2013

  3. email=sonoojaiswal@javatpoint.com

  4. 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. |

    ArrayList vs Vector

Example of Java ArrayList

Let's see a simple example where we are using ArrayList to store and traverse the elements.

  1. import java.util.*;

  2. class TestArrayList21{

  3. public static void main(String args[]){

  4. List<String> al=new ArrayList<String>();//creating arraylist

  5. al.add("Sonoo");//adding object in arraylist

  6. al.add("Michael");

  7. al.add("James");

  8. al.add("Andy");

  9. //traversing elements using Iterator

  10. Iterator itr=al.iterator();

  11. while(itr.hasNext()){

  12. System.out.println(itr.next());

  13. }

  14. }

  15. }

    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.

    1. import java.util.*;

    2. class TestVector1{

    3. public static void main(String args[]){

    4. Vector<String> v=new Vector<String>();//creating vector

    5. v.add("umesh");//method of Collection

    6. v.addElement("irfan");//method of Vector

    7. v.addElement("kumar");

    8. //traversing elements using Enumeration

    9. Enumeration e=v.elements();

    10. while(e.hasMoreElements()){

    11. System.out.println(e.nextElement());

    12. }

    13. }

    14. }

Test it Now

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

  1. public class Vector<E>

  2. extends Object<E>

  3. implements List<E>, Cloneable, Serializable

Java Vector Constructors

Vector class supports four types of constructors. These are given below:

SNConstructorDescription
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:

SNMethodDescription
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

  1. import java.util.*;

  2. public class VectorExample {

  3. public static void main(String args[]) {

  4. //Create a vector

  5. Vector<String> vec = new Vector<String>();

  6. //Adding elements using add() method of List

  7. vec.add("Tiger");

  8. vec.add("Lion");

  9. vec.add("Dog");

  10. vec.add("Elephant");

  11. //Adding elements using addElement() method of Vector

  12. vec.addElement("Rat");

  13. vec.addElement("Cat");

  14. vec.addElement("Deer");

  15. System.out.println("Elements are: "+vec);

  16. }

  17. }

  18. Output:

    Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
    

    Java Vector Example 2

    1. import java.util.*;

    2. public class VectorExample1 {

    3. public static void main(String args[]) {

    4. //Create an empty vector with initial capacity 4

    5. Vector<String> vec = new Vector<String>(4);

    6. //Adding elements to a vector

    7. vec.add("Tiger");

    8. vec.add("Lion");

    9. vec.add("Dog");

    10. vec.add("Elephant");

    11. //Check size and capacity

    12. System.out.println("Size is: "+vec.size());

    13. System.out.println("Default capacity is: "+vec.capacity());

    14. //Display Vector elements

    15. System.out.println("Vector element is: "+vec);

    16. vec.addElement("Rat");

    17. vec.addElement("Cat");

    18. vec.addElement("Deer");

    19. //Again check size and capacity after two insertions

    20. System.out.println("Size after addition: "+vec.size());

    21. System.out.println("Capacity after addition is: "+vec.capacity());

    22. //Display Vector elements again

    23. System.out.println("Elements are: "+vec);

    24. //Checking if Tiger is present or not in this vector

    25. if(vec.contains("Tiger"))

    26. {

    27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));

    28. }

    29. else

    30. {

    31. System.out.println("Tiger is not present in the list.");

    32. }

    33. //Get the first element

    34. System.out.println("The first animal of the vector is = "+vec.firstElement());

    35. //Get the last element

    36. System.out.println("The last animal of the vector is = "+vec.lastElement());

    37. }

    38. }

Test it Now

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

  1. import java.util.*;

  2. public class VectorExample2 {

  3. public static void main(String args[]) {

  4. //Create an empty Vector

  5. Vector<Integer> in = new Vector<>();

  6. //Add elements in the vector

  7. in.add(100);

  8. in.add(200);

  9. in.add(300);

  10. in.add(200);

  11. in.add(400);

  12. in.add(500);

  13. in.add(600);

  14. in.add(700);

  15. //Display the vector elements

  16. System.out.println("Values in vector: " +in);

  17. //use remove() method to delete the first occurence of an element

  18. System.out.println("Remove first occourence of element 200: "+in.remove((Integer)200));

  19. //Display the vector elements afre remove() method

  20. System.out.println("Values in vector: " +in);

  21. //Remove the element at index 4

  22. System.out.println("Remove element at index 4: " +in.remove(4));

  23. System.out.println("New Value list in vector: " +in);

  24. //Remove an element

  25. in.removeElementAt(5);

  26. //Checking vector and displays the element

  27. System.out.println("Vector element after removal: " +in);

  28. //Get the hashcode for this vector

  29. System.out.println("Hash code of this vector = "+in.hashCode());

  30. //Get the element at specified index

  31. System.out.println("Element at index 1 is = "+in.get(1));

  32. }

  33. }

Test it Now

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.

MethodsDescription
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

  1. import java.util.ArrayDeque;

  2. import java.util.Deque;

  3. public class JavaDequeExample1 {

  4. public static void main(String[] args) {

  5. Deque<Integer> deque = new ArrayDeque<Integer>();

  6. // Inserts the element.

  7. deque.add(1);

  8. deque.add(2);

  9. deque.add(3);

  10. System.out.println("Inserting three elements : ");

  11. for (Integer integer : deque) {

  12. System.out.println(integer);

  13. }

  14. // Popping the element.

  15. deque.pop();

  16. System.out.println("After popping : ");

  17. for (Integer integer : deque) {

  18. System.out.println(integer);

  19. }

  20. deque.remove(3);

  21. System.out.println("Removing the element 3 :"+deque);

  22. }

  23. }

Test it Now

Output:

Inserting three elements : 
1
2
3
After popping : 
2
3
Removing the element 3 :[2]

Example 2

  1. import java.util.ArrayDeque;

  2. import java.util.Deque;

  3. public class JavaDequeExample2 {

  4. public static void main(String[] args) {

  5. Deque<String> deque = new ArrayDeque<String>();

  6. // Adding the element in the front of the deque.

  7. deque.addFirst("Java");

  8. System.out.println("The first element is : "+deque);

  9. // Again adding the element in the front of the deque.

  10. deque.addFirst("Python");

  11. System.out.println("After adding the next element in the front of the deque : "+deque);

  12. deque.add("Ruby");

  13. System.out.println("The final deque is : "+deque);

  14. // Returns the number of elements.

  15. int size = deque.size();

  16. System.out.println("The number of elements are : "+size);

  17. // Removes the last element.

  18. deque.removeLast();

  19. System.out.println("Deque after removing the last element is given as : "+deque);

  20. }

  21. }

Test it Now

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

  1. public class ConcurrentHashMap<K,V>

  2. extends AbstractMap<K,V>

  3. implements ConcurrentMap<K,V>, Serializable

List of ConcurrentHashMap class Methods

NOMethodDescription
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()

  1. //import statement

  2. import java.util.concurrent.*;

  3. import java.util.*;

  4. public class ConcurrentHashMapcomputeIfAbsentExample1_1 {

  5. public static void main(String[] args)

  6. {

  7. // crete a HashMap and add some values

  8. HashMap<String, Integer> mapcon

  9. \= new HashMap<>();

  10. mapcon.put("k1", 100);

  11. mapcon.put("k2", 200);

  12. mapcon.put("k3", 300);

  13. mapcon.put("k4", 400);

  14. System.out.println("HashMap values :\n " + mapcon.toString());

  15. mapcon.computeIfAbsent("k5", k -> 200 + 300);

  16. mapcon.computeIfAbsent("k6", k -> 60 * 10);

  17. System.out.println("New HashMap after computeIfAbsent :\n "+ mapcon);

  18. }

  19. }

Test it Now

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()

  1. import java.util.*;

  2. import java.util.concurrent.*;

  3. public class ConcurrentHashMapcontainsValueExample1_1 {

  4. public static void main(String[] args)

  5. {

  6. ConcurrentHashMap<String, Integer> mymap = new ConcurrentHashMap<String, Integer>();

  7. mymap.put("AAA", 10);

  8. mymap.put("BBB", 15);

  9. mymap.put("CCC", 25);

  10. mymap.put("DDD", 255);

  11. mymap.put("EEE",30);

  12. System.out.println(" Mappings are: " +mymap);

  13. System.out.println("is 255 present? :: "

    • mymap.containsValue(255));
  14. }

  15. }

Test it Now

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

MethodsDescription
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

  1. import java.util.concurrent.ConcurrentLinkedQueue;

  2. public class JavaConcurrentLinkedQueueExample1 {

  3. public static void main(String[] args) {

  4. int j =1;

  5. ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();

  6. for (int i = 1; i <=5; i++) {

  7. // Adding items to the tail of this queue

  8. queue.add(i);}

  9. //inserts the element at the tail of this queue

  10. queue.offer(6);

  11. System.out.println("Queue : "+queue);

  12. //Returns true if this queue contains the specified element

  13. if(queue.contains(4)){

  14. System.out.println("This queue conatins 4");

  15. }

  16. else{

  17. System.out.println("4 is absent");

  18. }

  19. //returns true if the queue is empty

  20. if(queue.isEmpty()){

  21. System.out.println("Add some elements because the queue is empty.");

  22. }

  23. else{

  24. System.out.println("Queue is not empty");

  25. }

  26. }

  27. }

Test it Now

Output:

Queue : [1, 2, 3, 4, 5, 6]
This queue conatins 4
Queue is not empty

Example 2

  1. import java.util.ArrayList;

  2. import java.util.List;

  3. import java.util.concurrent.ConcurrentLinkedQueue;

  4. public class JavaConcurrentLinkedQueueExample2 {

  5. public static void main(String[] args) {

  6. ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();

  7. List<Integer> list = new ArrayList<Integer>();

  8. queue.add(11);

  9. queue.add(100);

  10. queue.add(122);

  11. queue.add(102);

  12. queue.add(112);

  13. list.add(11);

  14. list.add(100);

  15. System.out.println("Elements in queue : "+queue);

  16. //remove() method will remove the specified element from the queue

  17. queue.remove(122);

  18. queue.remove(102);

  19. System.out.println("Remaining elements in queue : "+queue);

  20. //Removes all the elements of this in queue which are present in the list

  21. queue.removeAll(list);

  22. System.out.println("Elemts of the list will get removed : "+queue);

  23. //Retain only those elements in this queue that are present in the list

  24. queue.retainAll(list);

  25. System.out.println("Queue will retain the elements of the list: "+queue);

  26. }

  27. }

Test it Now

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

  1. public class ConcurrentHashMap<K,V>

  2. extends AbstractMap<K,V>

  3. implements ConcurrentMap<K,V>, Serializable

List of ConcurrentHashMap class Methods

NOMethodDescription
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()

  1. //import statement

  2. import java.util.concurrent.*;

  3. import java.util.*;

  4. public class ConcurrentHashMapcomputeIfAbsentExample1_1 {

  5. public static void main(String[] args)

  6. {

  7. // crete a HashMap and add some values

  8. HashMap<String, Integer> mapcon

  9. \= new HashMap<>();

  10. mapcon.put("k1", 100);

  11. mapcon.put("k2", 200);

  12. mapcon.put("k3", 300);

  13. mapcon.put("k4", 400);

  14. System.out.println("HashMap values :\n " + mapcon.toString());

  15. mapcon.computeIfAbsent("k5", k -> 200 + 300);

  16. mapcon.computeIfAbsent("k6", k -> 60 * 10);

  17. System.out.println("New HashMap after computeIfAbsent :\n "+ mapcon);

  18. }

  19. }

Test it Now

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()

  1. import java.util.*;

  2. import java.util.concurrent.*;

  3. public class ConcurrentHashMapcontainsValueExample1_1 {

  4. public static void main(String[] args)

  5. {

  6. ConcurrentHashMap<String, Integer> mymap = new ConcurrentHashMap<String, Integer>();

  7. mymap.put("AAA", 10);

  8. mymap.put("BBB", 15);

  9. mymap.put("CCC", 25);

  10. mymap.put("DDD", 255);

  11. mymap.put("EEE",30);

  12. System.out.println(" Mappings are: " +mymap);

  13. System.out.println("is 255 present? :: "

    • mymap.containsValue(255));
  14. }

  15. }

Test it Now

Output:

Mappings are: {AAA=10, CCC=25, BBB=15, EEE=30, DDD=255}
is 255  present? ::  true