Showing posts with label Java collections framework. Show all posts
Showing posts with label Java collections framework. Show all posts

Monday, July 8, 2024

How ArrayList Works Internally in Java

ArrayList arguably would be the most used collection along with the HashMap. Many of us programmers whip up code everyday which contains atleast one of these data structures to hold objects. I have already discussed how HashMap works internally in Java, in this post I'll try to explain how ArrayList internally works in Java.

As most of us would already be knowing that ArrayList is a Resizable-array implementation of the List interface i.e. ArrayList grows dynamically as the elements are added to it. So let's try to get clear idea about the following points-

  • How ArrayList is internally implemented in Java.
  • What is the backing data structure for an ArrayList.
  • How it grows dynamically and ensures that there is always room to add elements.

Because of all these side questions it is also a very important Java Collections interview question.

Note that the code of ArrayList used here for reference is from Java 17


Where does ArrayList internally store elements

Basic data structure used by Java ArrayList to store objects is an array of Object class, which is defined as follows-

transient Object[] elementData;

I am sure many of you would be thinking why transient and how about serializing an ArrayList then?
ArrayList provides its own version of readObject and writeObject methods so no problem in serializing an ArrayList and that is the reason, I think, of making this Object array as transient.

Sunday, July 7, 2024

ArrayList in Java With Examples

Java ArrayList is one of the most used collection and most of its usefulness comes from the fact that it grows dynamically. Contrary to arrays you don't have to anticipate in advance how many elements you are going to store in the ArrayList. As and when elements are added ArrayList keeps growing, if required.

Though internally it is not really some "elastic" array which keeps growing, it is as simple as having an array with an initial capacity (default is array of length 10). When that limit is crossed another array is created which is 1.5 times the original array and the elements from the old array are copied to the new array.

Refer How does ArrayList work internally in Java to know more about how does ArrayList work internally in Java.


Hierarchy of the ArrayList

To know the hierarchy of java.util.ArrayList you need to know about 2 interfaces and 2 abstract classes.

  • Collection Interface- Collection interface is the core of the Collection Framework. It must be implemented by any class that defines a collection.
  • List interface- List interface extends Collection interface. Apart from extending all the methods of the Collection interface, List interface defines some methods of its own.
  • AbstractCollection- Abstract class which implements most of the methods of the Collection interface.
  • AbstractList- Abstract class which extends AbstractCollection and implements most of the List interface.

ArrayList extends AbstractList and implements List interface too. Apart from List interface, ArrayList also implements RandomAccess, Cloneable, java.io.Serializable interfaces.

Tuesday, March 12, 2024

Fail-Fast Vs Fail-Safe Iterator in Java

Difference between fail-fast and fail-safe iterator in Java, apart from being an important Java Collections interview questions, is a very important concept to know. The collections which are there from Java 1.2 (or even legacy) like ArrayList, Vector, HashSet all have fail-fast iterator whereas Concurrent collections added in Java 1.5 like ConcurrrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet have fail-safe iterator.

So first let us see the key differences between the fail-fast and fail-safe iterator in Java and then we'll see some Java programs to explain those features.

Friday, February 16, 2024

Difference Between ArrayList And Vector in Java

In many ways Vector class in Java is just like ArrayList apart from some differences and this post is about those differences between the ArrayList and Vector in Java.

There are many similarities between Vector and ArrayList classes in Java. Vector, just like ArrayList, is also a growable dynamic array. As of Java v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework.

With JDK 5 it was also retrofitted for generics and implements Iterable interface too which means it can also use enhanced for loop.

ArrayList Vs Vector in Java

  • ArrayList is not synchronized whereas Vector is Synchronized. Which means that the methods in the Vector class are Synchronized making Vector thread-safe and ready to use as-is in a multi-threaded environment.
    ArrayList, if needed in a multi-threaded environment, has to be synchronized externally using Collections.synchronizedList method which returns a synchronized (thread-safe) list backed by the specified list.
  • Refer How and why to synchronize ArrayList in Java to know how to synchronize an ArrayList.

  • A Vector, by default, doubles the size of its array when it needs to expand the array, while the ArrayList increases its array size by 50 percent.
  • As mentioned though Vector is retrofitted to implement the List interface it still has legacy methods which are not there in ArrayList. As Example methods like addElement(), removeElement(), capacity() which are there in Vector class but not in ArrayList.
  • Performance wise Vector is comparatively slower than the ArrayList because it is synchronized. That means only one thread can access method of Vector at the time and there is an overhead of acquiring lock on the object too.
  • For traversing an ArrayList as well as Vector, Iterator or ListIterator can be used. That Iterator/ListIterator is fail-fast and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method.
    For Vector enumeration can also be used for traversing which is not fail-fast.

That's all for this topic Difference Between ArrayList And Vector in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between ArrayList And LinkedList in Java
  2. Difference Between Array And ArrayList in Java
  3. Difference Between ArrayList And CopyOnWriteArrayList in Java
  4. How to Remove Elements From an ArrayList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How to Sort HashSet in Java
  3. Difference Between Comparable and Comparator in Java
  4. Polymorphism in Java
  5. Array in Java With Examples
  6. finalize method in Java
  7. Nested Try Statements in Java Exception Handling
  8. Spring Boot Event Driven Microservice With Kafka

Tuesday, January 9, 2024

How HashMap Works Internally in Java

In this Java tutorial you'll learn how HashMap works internally in Java, which is also a favorite Java Collections interview question. Note that code snippets used here are from JDK 17.

There are four things you should know about HashMap before going into internal working of HashMap in Java-

  • HashMap works on the principal of hashing.
  • Map.Entry interface- This interface gives a map entry (key-value pair). HashMap in Java stores both key and value object, in bucket, as an object of Node class which implements this nested interface Map.Entry. Read more about Map.Entry interface here.
  • hashCode()- HashMap provides put(key, value) method for storing and get(key) method for retrieving values from HashMap. When put() method is used to store (Key, Value) pair, HashMap implementation calls hashcode on Key object to calculate a hash that is used to find a bucket where Entry object will be stored.
    When get() method is used to retrieve value, again key object (passed with the get() method) is used to calculate a hash which is then used to find a bucket where that particular key is stored.
  • equals()- equals() method is used to compare objects for equality. In case of HashMap key object is used for comparison, also using equals() method Map knows how to handle hashing collision (hashing collision means more than one key having the same hash value, thus assigned to the same bucket). In that case objects are stored in a linked list, refer figure for more clarity.
    Where hashCode() method helps in finding the bucket where that key is stored, equals() method helps in finding the right key as there may be more than one key-value pair stored in a single bucket.

** Bucket term used here is actually an index of array, that array is called table in HashMap implementation. Thus table[0] is referred as bucket0, table[1] as bucket1 and so on.


How elements are stored internally in Java HashMap

HassMap class in Java internally uses an array called table of type Node to store the elements which is defined in the HashMap class as-

transient Node<K,V>[] table;
Node is defined as a static class with in a Hashmap.
static class Node<K,V> implements Map.Entry<K,V> {
  final int hash;
  final K key;
  V value;
  Node<K,V> next;
  ..
  ..  
}

As you can see for each element four things are stored in the following fields-

  • hash- For storing Hashcode calculated using the key.
  • key- For holding key of the element.
  • value- For storing value of the element.
  • next- To store reference to the next node when a bucket has more than one element and a linkedlist is formed with in a bucket to store elements.

Following image shows how Node(key-value pair) objects are stored internally in table array of the HashMap class.

HashMap internal implementation in Java

Importance of hashCode() and equals() method in HashMap

How important it is to have a proper hash code and equals method can be seen through the help of the following program, explanation of this example will also help in understanding the working of HashMap's put()method (next section).

public class HashMapTest {
  public static void main(String[] args) {
    Map <Key, String> cityMap = new HashMap<Key, String>();
    cityMap.put(new Key(1, "NY"),"New York City" );
    cityMap.put(new Key(2, "ND"), "New Delhi");
    cityMap.put(new Key(3, "NW"), "Newark");
    cityMap.put(new Key(4, "NP"), "Newport");

    System.out.println("size before iteration " + cityMap.size());
    Iterator <Key> itr = cityMap.keySet().iterator();
    while (itr.hasNext()){
      System.out.println(cityMap.get(itr.next()));     
    }
    System.out.println("size after iteration " + cityMap.size());    
  }
}

// This class' object is used as key
// in the HashMap
class Key{
  int index;
  String Name;
  Key(int index, String Name){
    this.index = index;
    this.Name = Name;
  }
 
  @Override
  // A very bad implementation of hashcode
  // done here for illustrative purpose only 
  public int hashCode(){
    return 5;
  }
 
  @Override
  // A very bad implementation of equals
  // done here for illustrative purpose only 
  public boolean equals(Object obj){
    return true;
  }
}

Output

size before iteration 1
Newport
size after iteration 1

Refer Overriding hashCode() and equals() method in Java to know more about hashCode() and equals() methods.

How put() method of Java HashMap works internally

Lets get through the above example to see what is happening, this will also help in understanding how put() method of HashMap works internally.

Notice that I am inserting 4 values in the HashMap, still in the output it says size is 1 and iterating the map gives me the last inserted entry. Why is that? Answer lies in, how hashCode() and equals() method are implemented for the key Class. Have a look at the hashCode() method of the class Key which always returns "5" and the equals() method which is always returning "true".

When a value is put into HashMap it calculates a hash using key object and for that it uses the hashCode() method of the key object class (or its parent class). Based on the calculated hash value HashMap implementation decides which bucket should store the particular Entry object.

In my code the hashCode() method of the key class always returns "5". This effectively means, calculated hash value, is same for all the entries inserted in the HashMap. Thus all the entries are stored in the same bucket.

HashMap implementation uses equals() method to see if the key is equal to any of the already inserted keys (Recall that there may be more than one entry in the same bucket). Note that, with in a bucket key-value pair entries (Entry objects) are stored in a linked-list (Refer figure for more clarity). In case hash is same, but equals() returns false (which essentially means more than one key having the same hash or hash collision) Entry objects are stored, with in the same bucket, in a linked-list.

In my code, I am always returning true for equals() method so the HashMap implementation "thinks" that the keys are equal and overwrites the value. So, in a way using hashCode() and equals() I have "tricked" HashMap implementation to think that all the keys (even though different) are same, thus overwriting the values.

In a nutshell there are three steps in the internal implementation of HashMap put() method-

  • Using hashCode() method, hash value will be calculated. In which bucket particular entry will be stored is ascertained using that hash.
  • equals() method is used to find if such a key already exists in that bucket, if not found then a new node is created with the map entry and stored within the same bucket. A linked-list is used to store those nodes.
  • If equals() method returns true, it means that the key already exists in the bucket. In that case, the new value will overwrite the old value for the matched key.

How Java HashMap get() method works internally

As we already know how Entry objects are stored in a bucket and what happens in the case of Hash Collision it is easy to understand what happens when key object is passed in the get() method of the HashMap to retrieve a value.

Using the key (passed in the get() method) hash value will be calculated to determine the bucket where that Entry object is stored, in case there are more than one Entry object with in the same bucket (stored as a linked-list) equals() method will be used to find out the correct key. As soon as the matching key is found get() method will return the value object stored in the Entry object.

When null Key is inserted in a HashMap

HashMap in Java also allows null as key, though there can only be one null key in HashMap. While storing the Entry object HashMap implementation checks if the key is null, in case key is null, it is always mapped to bucket 0, as hash is not calculated for null keys.

HashMap implementation changes in Java 8

Though HashMap implementation in Java provides constant time performance O(1) for get() and put() methods but that is in the ideal case when the Hash function distributes the objects evenly among the buckets.

But the performance may worsen in the case hashCode() used is not proper and there are lots of hash collisions. As we know now that in case of hash collision entry objects are stored as a node in a linked-list and equals() method is used to compare keys. That comparison to find the correct key with in a linked-list is a linear operation so in a worst case scenario the complexity becomes O(n).

To address this issue in Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached. Which means HashMap starts with storing Entry objects in linked list but after the number of items in a hash becomes larger than a certain threshold, the hash changes from using a linked list to a balanced tree, this improves the worst case performance from O(n) to O(log n).

Points to note-

  • HashMap works on the principal of hashing.
  • HashMap in Java uses the hashCode() method to calculate a hash value. Hash value is calculated using the key object. This hash value is used to find the correct bucket where Entry object will be stored.
  • HashMap uses the equals() method to find the correct key whose value is to be retrieved in case of get() and to find if that key already exists or not in case of put().
  • With in the internal implementation of HashMap hashing collision means more than one key having the same hash value, in that case Entry objects are stored as a linked-list with in a same bucket.
  • With in a bucket values are stored as Entry objects which contain both key and value.
  • In Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached while storing values. This improves the worst case performance from O(n) to O(log n).

That's all for this topic How HashMap Works Internally in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How LinkedList Class Works Internally in Java
  3. How HashSet Works Internally in Java
  4. How to Loop Through a Map in Java
  5. ConcurrentHashMap in Java With Examples

You may also like-

  1. strictfp in Java
  2. Constructor Chaining in Java
  3. Interface Static Methods in Java
  4. Method reference in Java 8
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Try-With-Resources in Java With Examples
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Count Number of Times Each Character Appears in a String Java Program

Tuesday, January 2, 2024

How to Sort an ArrayList in Descending Order in Java

In Java ArrayList elements are added in sequential order and while iterating an ArrayList same sequential order will be used to retrieve the elements. Sometimes you may have a requirement to sort an ArrayList in ascending or descending order. In this post we'll see how to sort an ArrayList in descending order in Java.

Sorting ArrayList in descending order

For sorting ArrayList in descending order in Java there are following options

  1. Use method reverseOrder() provided by Collections class. See example.
  2. General form and description

    public static <T> Comparator<T> reverseOrder()
    

    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

    There is also a Comparator.reverseOrder() method Java 8 onward that can also be used.

  3. Using a custom comparator. See example.

  4. You can also sort Java ArrayList in descending order using Java Stream API's sorted() method and then collect it into a separate List. That way you can retain the original list. See example.

You must also know about the overloaded sort method provided by the Collections class.

  • public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).

Sorting ArrayList Using reverseOrder method

reverseOrder() method mentioned above can be provided as the second parameter in the sort() method mentioned above and you will get the ArrayList sorted in reverse order. Let's see an example.

In the program Collections.reverseOrder() method is passed as an argument to the Collections.sort() method to sort ArrayList in reverse order.

public class SortListDemo {
  public static void main(String[] args) {
    // Using diamond operator (Right side no type specified)
    // Available from Java7 onwards
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // sorting the list in descending order
    Collections.sort(cityList, Collections.reverseOrder());
    //Displaying the list
    for(String city : cityList){
      System.out.println("Name " + city);
    }
  }
}

Output

Name Mumbai
Name Mumbai
Name Kolkata
Name Delhi
Name Chennai
Name Bangalore

Java 8 onward there is also a Comparator.reverseOrder() method that can be used to sort an ArrayList in descending order in Java.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
    cityList.sort(Comparator.reverseOrder());
    System.out.println(cityList);

  }
}

Sorting Java ArrayList Using custom Comparator

Internally reverseOrder method calls a Comparator class to do the sorting in reverse order. You can do it yourself too by writing your own comparator class. Writing your own Comparator gives you more control over the object ordering.

public class SortListDemo {
  public static void main(String[] args) {
    // Using diamond operator (Right side no type specified)
    // Available from Java7 onwards
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // sorting the list in descending order
    Collections.sort(cityList, new MyComparator());
    //Displaying the list
    for(String city : cityList){
      System.out.println("Name " + city);
    }
  }
}

//Custom comparator class
class MyComparator implements Comparator<String>{
  @Override
  public int compare(String o1, String o2) {
    return o2.compareTo(o1);
  }    
}

Sorting Java ArrayList Using Java Stream sorted()

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortListDemo {
  public static void main(String[] args) {
    
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
   
    List<String> sortedList = cityList.stream()
                                      .sorted(Comparator.reverseOrder())
                                      .collect(Collectors.toList());
    System.out.println(sortedList);
  }
}

That's all for this topic How to Sort an ArrayList in Descending Order in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. How LinkedList Class Works Internally in Java
  5. CopyOnWriteArrayList in Java - The thread safe variant of ArrayList

You may also like-

  1. How HashMap Works Internally in Java
  2. Difference Between CountDownLatch And CyclicBarrier in Java
  3. Java Phaser With Examples
  4. Varargs (Variable-length Arguments) in Java
  5. What if run() method called directly instead of start() method
  6. static reference to the non-static method or field error
  7. Method overloading in Java
  8. Creating Custom Exception Class in Java

Monday, January 1, 2024

Difference Between Array And ArrayList in Java

Difference between Array and ArrayList in Java is one question you may come across in a Java technical interview. Though performance wise both Array and ArrayList may give almost similar performance but functionality wise they both are used in quite different scenarios.

In this post we'll see some of the differences between ArrayList and Array in terms of how they are initialized and the performance they give.

Array Vs ArrayList in Java

  1. First and the most important difference is Array is static and can't be resized once declared.
    Whereas ArrayList is dynamic and that is why also known as dynamic array. ArrayList also uses array of Object internally, but it has the logic to keep growing the size of the array as and when previous size is not able to fit in the number of elements stored in the ArrayList.
  2. Refer: How ArrayList works internally in Java to know more about the internal implementation of ArrayList.

  3. Array can store both primitive types as well as objects whereas ArrayList can store only objects. Though Autoboxing and Unboxing has blurred that difference, but the important point to note here is that in case of ArrayList any primitive data type is still wrapped and stored as an Object.

    For example, if you want an array of primitive type int-

    int[] intArray = new int[3];
    

    Or, if you have a class Employee and you want an array of size 5 to hold 5 Employee objects then-

    Employee[] employees = new Employee[5];
    

    In case of ArrayList if you want to store integers then you have to do this, note the use of wrapper class Integer-

    List<Integer> myList = new ArrayList<Integer>();
    
  4. Difference number 2 between array and ArrayList also indicates one more difference, which is about "type safety". Since Array knows the type of the data which it can hold so it will give compiler error "Type Mismatch" or "ArrayStoreException" if it is not able to resolve it at run time. For example following code throws ArrayStoreException.
    Object[] names = new String[3];
    names[0] = 12;
    
    Where as following code throws compile time error "Type Mismatch".
    String[] names = new String[3];
    names[0] = 12;
    

    In case of ArrayList, generics brought the much needed type safety which, as shown above, is not required for Array as type of elements stored in the array is specified at the array creation time itself, trying to store element of any other type will result in ArrayStoreException.

    If a list, which stores only Integers, is needed it should be defined as-

    List<Integer> myList = new ArrayList<Integer>();
    
  5. Performance wise both Array and ArrayList are almost similar as ArrayList also uses array of Objects internally and both are index based. But there is some overhead in case of ArrayList if there are more elements and the internal array has to be resized.
    Since ArrayList stores only objects so memory usage is also more than the array.
  6. Array has length variable which gives the length of the array. Note that length attribute denotes the length of the array at the time of declaration.
    For example, If an array is declared like this-
    String[] names = new String[3];
    names[0] = "Java";
    
    Then length var will always be 3 even if array names has only one value.

    In case of ArrayList, size() method is used and it will give the size as the current number of elements in the ArrayList.

That's all for this topic Difference Between Array And ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between ArrayList And LinkedList in Java
  2. Difference Between ArrayList And Vector in Java
  3. Difference Between ArrayList And CopyOnWriteArrayList in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. TreeMap in Java With Examples
  3. Polymorphism in Java
  4. Method overriding in Java
  5. Race condition in Java multi-threading
  6. Java ThreadLocal Class With Examples
  7. Lambda expression and exception handling
  8. Dependency Injection in Spring Framework

Wednesday, January 18, 2023

HashMap Vs LinkedHashMap Vs TreeMap in Java

Though HashMap, LinkedHashMap and TreeMap all are implementations of the Map interface and share some traits like

But there are certain differences too related to how elements are ordered, performance etc. So it is very important to know these differences among HashMap, LinkedHashMap and TreeMap in Java as it will help you to make an informed choice about which Map implementation should be used to meet the requirement.

Differences among HashMap, LinkedHashMap and TreeMap in Java

  1. First and most important difference is related to Ordering of the elements.
    HashMap makes no guarantees as to the order of the map.
    LinkedHashMap maintains the insertion order or access order (based on the constructor) of the elements. Which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map or the order in which its entries were last accessed, from least-recently accessed to most-recently.
    TreeMap stores objects in sorted order. The elements in TreeMap are ordered according to the natural ordering of its keys or a Comparator can be provided at map creation time to provide custom ordering of its keys.

  2. Another difference is related to allowing null as key or value.
    HashMap as well as LinkedHashMap allows one null as key, multiple values may be null though.
    TreeMap does not allow null as key. Any attempt to add null in a TreeMap will result in a NullPointerException. Values may be null.

  3. For HashMap and LinkedHashMap comparison of the elements is done using equals() method.
    As Example in get method for the passed key k, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null.
    TreeMap does the comparison of the keys using the compareTo (or compare) method, depending on whether sorting is done using Comparable or Comparator.
    As Example in get method for the passed key k, if this map contains a mapping from a key k to a value v such that key compares equal to k according to the map's ordering, then this method returns v; otherwise it returns null.

  4. HashMap class extends AbstractMap and implements Map interface.
    LinkedHashMap class extends HashMap and implements Map interface.
    TreeMap class extends AbstractMap and implements NavigableMap interface.

  5. HashMap stores elements in a bucket which actually is an index of the array which means the backing data structure for the HashMap is an array where bucket0 means index[0], bucket1 means index[1] of that array.
    LinkedHashMap extends HashMap and uses the same internal implementation as HashMap. Apart from that it also maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering.
    TreeMap is a Red-Black tree based NavigableMap implementation.

  6. Performance wise HashMap provides constant time performance O(1) for get() and put() method but that is in the ideal case when the Hash function distributes the objects evenly among the buckets. In worst case when equals() and HashCode() implementation is not good it may even become O(n).
    LinkedHashMap also provides constant time performance O(1) for get() and put() method but in general a little slower than the HashMap as it has to maintain a doubly linked list.
    TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

That's all for this topic HashMap Vs LinkedHashMap Vs TreeMap in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between HashMap And Hashtable in Java
  2. How to Loop Through a Map in Java
  3. LinkedHashMap in Java With Examples
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. How to Sort ArrayList of Custom Objects in Java
  3. Deadlock in Java Multi-Threading
  4. Difference Between sleep And wait in Java Multi-Threading
  5. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  6. Java Pass by Value or Pass by Reference
  7. Serialization Proxy Pattern in Java
  8. Creating Custom Exception Class in Java

Saturday, December 24, 2022

Difference Between HashMap And Hashtable in Java

Though both Hashtable and HashMap in Java have some similarities like storing elements as a (key, value) pair and using hashing technique to store elements. From Java V1.2, Hashtable class was also retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Still there are some differences in these two data structures. In this post we'll see those differences between HashMap and Hashtable in Java.

HashMap Vs Hashtable in Java

  • HashMap is not synchronized where as Hashtable is synchronized. Which essentially means that Hashtable is inherently thread safe where as HashMap is not. If we need to synchronize a HashMap then that has to be done explicitly by calling the following method.
    Map m = Collections.synchronizedMap(hashMap);
    
  • HashMap allows one null value as a key and any number of null values.
    Hashtable does not allow null values either as key or as value.
  • For traversing a HashMap an iterator can be used. That iterator is fail-fast and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method.
    For traversing a Hashtable either an iterator or Enumerator can be used. Here again the iterator is fail-fast where as Enumerator is fail-safe.
    public class HashTableDemo {
      public static void main(String[] args) {
        Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);
        // Using enumerator
        for (Enumeration<String> e = numbers.keys(); e.hasMoreElements();){
          System.out.println(e.nextElement());
          numbers.put("four", 4);
        }
    
        // Using iterator
        Iterator<String> itr =  numbers.keySet().iterator();
        while (itr.hasNext()){
          System.out.println(numbers.get(itr.next()));
          numbers.put("five", 5);
        }  
      }
    }
    

    Output

    two
    one
    three
    four
    2
    Exception in thread "main" java.util.ConcurrentModificationException
     at java.util.Hashtable$Enumerator.next(Unknown Source)
     at org.netjs.prog.HashTableDemo.main(HashTableDemo.java:22)
    

    Here it can be seen that while enumerating a Hashtable if a new value is added (i.e. Hashtable is structurally modified) that doesn't throw any exception. Whereas, if a new value is added, while iterating it throws a ConcurrentModificationException.

  • Performance wise HashMap is faster than the Hashtable reason being HashMap is not synchronized.

That's all for this topic Difference Between HashMap And Hashtable in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashMap Works Internally in Java
  2. LinkedHashMap in Java With Examples
  3. TreeMap in Java With Examples
  4. Difference Between HashMap And ConcurrentHashMap in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. static Reference to The Non-static Method or Field Error
  2. Abstraction in Java
  3. ThreadLocal class in Java With Examples
  4. Setter-based dependency injection in Spring
  5. How to Remove Duplicate Elements From an ArrayList in Java
  6. EnumSet in Java With Examples
  7. Java BlockingQueue With Examples
  8. @FunctionalInterface Annotation in Java

Friday, October 28, 2022

Java Map size() With Examples

If you want to know how many key-value pair are there in a Map you can use size() method which returns the number of key-value mappings in the map.

Syntax of the size() method is

int size()

Method doesn't take any parameters.

Method returns an int value denoting the number of key-value mappings in the map

size() method Java example

Here we have a HashMap with some key, value pair added. Using size() method we'll get the current size of the map.

import java.util.HashMap;
import java.util.Map;

public class SizeMapDemo {
  public static void main(String[] args) {
    Map<String, String> cityMap = new HashMap<String, String>();
    // Adding elements
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Beijing");
    cityMap.put("5", "Berlin");
    
    int sizeOfMap = cityMap.size();
    System.out.println("Number of entries in the Map: " + sizeOfMap);
  }
}

Output

Number of entries in the Map: 5

That's all for this topic Java Map size() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. removeIf() Method in Java Collection With Examples
  2. Java Map putIfAbsent() With Examples
  3. Java Map replace() With Examples
  4. Difference Between ArrayList And LinkedList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. CopyOnWriteArrayList in Java With Examples
  3. Type Wrapper Classes in Java
  4. Why Class Name And File Name Should be Same in Java
  5. Convert String to Char Array in Java
  6. Python First Program - Hello World
  7. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  8. What is SafeMode in Hadoop

Thursday, October 27, 2022

removeIf() Method in Java Collection With Examples

In this post we'll see how to use removeIf() method to remove elements from the Collection that satisfy the given condition. The removeIf() method is included in java.util.Collection interface in Java 8. Since it is part of Collection interface so you can use it with Collections like ArrayList, HashSet that implements Collection interface. To use it with HashMap you will have to get a collection view of the Map, since Map doesn't implement Collection interface.


Java removeIf() method syntax

boolean removeIf(Predicate<? super E> filter)

Parameter passed to this method is of type Predicate functional interface, which can be implemented as a boolean-valued function with one argument.

Method returns true if any elements were removed.

Removing elements from ArrayList using removeIf() method

In this example we'll have a list of cities and we'll remove elements from this ArrayList using removeIf() method. In passed Predicate if the condition holds true for any of the elements, then that element is removed from the list.

import java.util.ArrayList;
import java.util.List;

public class RemoveIf {

  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    System.out.println("*** List Initially ***");
    System.out.println(cityList);
    cityList.removeIf(p -> p.equalsIgnoreCase("Hyderabad") || 
          p.equalsIgnoreCase("Bangalore"));
    System.out.println("After Removal " + cityList);
  }
}

Output

*** List Initially ***
[Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]
After Removal [Delhi, Mumbai, Kolkata, Mumbai]

Removing elements from HashSet using removeIf() method

You can use removeIf() method with HashSet also to remove elements from the Set based on the passed condition. In the given example condition is to remove cities having name of length more than 6.

import java.util.HashSet;
import java.util.Set;

public class RemoveIf {

  public static void main(String[] args) {
    // creating a HashSet
    Set<String> citySet = new HashSet<String>();
    // Adding elements
    citySet.add("London");        
    citySet.add("Tokyo");
    citySet.add("New Delhi");
    citySet.add("Beijing");
    citySet.add("Nairobi");
    System.out.println("*** Set Initially ***");
    System.out.println(citySet);
    
    // Remove all cities having length more than 6
    citySet.removeIf(e -> e.length() > 6);
    System.out.println("After Removal " + citySet);
  }
}

Output

*** Set Initially ***
[Beijing, New Delhi, Nairobi, Tokyo, London]
After Removal [Tokyo, London]

Removing elements from HashMap using removeIf() method

To use removeIf() method with a Map you have to get Collection view of a Map. After getting the Collection view of a Map removeIf() method can be used.

import java.util.HashMap;
import java.util.Map;


public class RemoveIf {

  public static void main(String[] args) {
    Map<String, String> cityMap = new HashMap<String, String>();
    // Adding elements
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Beijing");
    cityMap.put("5", "Berlin");

    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    // Use entrySet to get Set view of all Map entries. 
    // Remove entry from Map based on the condition for value.
    cityMap.entrySet().removeIf(entry -> entry.getValue().equals("Beijing"));
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Beijing, 5=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai, 5=Berlin}

That's all for this topic removeIf() Method in Java Collection With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Entry From HashMap in Java
  2. How to Remove Elements From an ArrayList in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Java Map replace() With Examples
  5. HashSet Vs LinkedHashSet Vs TreeSet in Java

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. CopyOnWriteArraySet in Java With Examples
  3. Switch Expressions in Java 12
  4. Java Nested Class And Inner Class
  5. Reading File in Java Using Files.lines And Files.newBufferedReader
  6. Angular Cross Component Communication Using Subject Observable
  7. Angular HttpClient - Set Response Type as Text
  8. Spring Web MVC Tutorial

Wednesday, October 26, 2022

How to Remove Elements From an ArrayList in Java

To remove elements from an ArrayList in Java you have the following options.

  • You can use remove() method provided by ArrayList class to remove an object from ArrayList.
  • You can use remove() method provided by Iterator.
  • There is a removeIf() method too in ArrayList class that can be used Java 8 onwards to remove elements from ArrayList in Java.

In this post we'll see when to use which method and why.


ArrayList remove() method

ArrayList provides two overloaded remove methods for removing element from an ArrayList in Java-

  • remove(int index)- This method takes int (which specifies the index in the list) as parameter and removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
  • public boolean remove(Object o)- This method takes the object, which has to be removed as parameter and removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged.

If you are just removing an element from an ArrayList without looping the list then you can remove an element by giving its index in the list or specifying the object itself.

import java.util.ArrayList;
import java.util.List;

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    System.out.println("Original List- " + cityList);
    cityList.remove(1);
    
    cityList.remove("Mumbai");
    System.out.println("List after removing elements- " + cityList);
  }
}

Output

Original List- [Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]
List after removing elements- [Delhi, Kolkata, Hyderabad, Bangalore]

Removing element from ArrayList while iterating the list

Note that using ArrayList's remove method with enhanced for loop or iterator may result in ConcurrentModificationException as the iterators returned by ArrayList class's iterator and ListIterator methods are fail-fast. Which means if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)

Example code

Here is an example where ArrayList's remove() method is used while iterating a list using For-Each loop. As you can see ConcurrentModificationException is thrown.

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
               
    for(String city : cityList){
      if(city.equalsIgnoreCase("Kolkata"))
        cityList.remove(city);
    }
  }
}

Output

Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
 at java.util.ArrayList$Itr.next(Unknown Source)
 at org.netjs.prog.RemoveFromListDemo.main(RemoveFromListDemo.java:20)

Using Iterator's remove method to remove element from ArrayList

While looping if you want to remove any element from an ArrayList you should use use Iterator's remove method so that ConcurrentModificationException is not thrown.

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
                
    Iterator<String> itr = cityList.iterator();
    int i = 0;
    while(itr.hasNext()){
      System.out.println("city " + itr.next());
      if(i == 3 || i == 4){
        itr.remove();
      }
      i++;
    }
    
    System.out.println("After deletion " );
    for(String city : cityList){
      System.out.println("city " + city);
    }
  }
}

Output

city Delhi
city Mumbai
city Kolkata
city Hyderabad
city Bangalore
city Mumbai
After deletion 
city Delhi
city Mumbai
city Kolkata
city Mumbai

Using ArrayList's remove() method with normal for loop

ArrayList's remove method can be used with normal for loop to remove an ArrayList in Java. If index is passed then it may give undesired result because of the fact that all the other elements are shifted to the left when an element is removed.
As example In the given program code if I want to remove the elements at index 3 & 4 then ideally Hyderabad and Bangalore should be removed from the list. Let's see what happens-

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    
    for(int i = 0; i < cityList.size(); i++){
      if(i == 3 || i == 4){
        cityList.remove(i);
      }
    }
    
    System.out.println("After deletion " );
    for(String city : cityList){
      System.out.println("city " + city);
    }
  }
}

Output

After deletion 
city Delhi
city Mumbai
city Kolkata
city Bangalore

It can be seen that Hyderabad is removed alright but Mumbai is removed instead of Bangalore. This happened because after Hyderabad is removed elements in the list are shifted and Bangalore came in the place of Hyderabad and Mumbai in place of Bangalore. Thus Mumbai was at index 4 hence removed.

In the previous code if we were using city(object) in the if condition then it would have run fine.

public class RemoveFromListDemo {

  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    
    for(int i = 0; i < cityList.size(); i++){
      String city = cityList.get(i);
      if(city.equalsIgnoreCase("Kolkata") || city.equalsIgnoreCase("Bangalore")){
        cityList.remove(city);
      }
    }    
    System.out.println("After deletion " + cityList);
  }
}

Output

After deletion [Delhi, Mumbai, Hyderabad, Mumbai]

Using removeIf() to remove element from ArrayList

If you are using Java 8, then removeIf() method can be used to remove element from ArrayList, which takes Predicate functional interface as a parameter. In that case we can write the removal code with in one line as-

cityList.removeIf(p -> p.equalsIgnoreCase("Hyderabad") || 
    p.equalsIgnoreCase("Bangalore"));

ArrayList remove method and AutoBoxing problem

While removing elements from an ArrayList of Integers we may get problem because of Autoboxing. As already mentioned there are two overloaded remove methods-

  • Remove(int index)
  • Remove(Object o)

If we give an int as parameter then it will always be treated as a call to remove method with int parameter.
Let's clear it with an example

public class RemoveFromListDemo {
  public static void main(String[] args) {
    
    List<Integer> numberList = new ArrayList<Integer>();
    // adding to list as int, no need to do
    // new Integer(1)
    numberList.add(1);
    numberList.add(2);
    numberList.add(3);
    numberList.add(4);
    
    // Removing by index 1
    numberList.remove(1);
    // This time removing the integer Object 4
    numberList.remove(4);
  }
}

Output

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
 at java.util.ArrayList.rangeCheck(Unknown Source)
 at java.util.ArrayList.remove(Unknown Source)
 at org.netjs.prog.RemoveFromListDemo.main(RemoveFromListDemo.java:20)

So, even if a user thinks while removing the second time that he is giving an object as parameter and hoping autoboxing will take care of all the wrapping to Integer Object chore it won't happen in this case. Second call will also be treated as a call to remove method with int parameter. First remove has already removed one element so now the list size is 3 and trying to access index 4 in such a list will throw IndexOutOfBoundsException.

So in this case user has to explicitly tell the compiler that remove method which takes object as parameter has to be called.

numberList.remove(new Integer(4)); 

That's all for this topic How to Remove Elements From an ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Remove Duplicate Elements From an ArrayList in Java
  3. How to Sort ArrayList in Java
  4. How to Join Lists in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. equals() And hashCode() Methods in Java
  2. How HashSet Works Internally in Java
  3. ConcurrentHashMap in Java With Examples
  4. Interface Static Methods in Java 8
  5. Method reference in Java 8
  6. Functional Interfaces in Java
  7. Static Synchronization in Java Multi-Threading
  8. java.lang.ClassCastException - Resolving ClassCastException in Java

Friday, October 21, 2022

Java Map replace() With Examples

The replace() method in java.util.Map is added in Java 8. The replace() method replaces the value associated with the specified key only if the key is already mapped to some value. That's how replace() method differs from put() method, if a key is passed to the put() method that doesn't already exist in the Map then it will add the entry (key, value pair) to the Map.

Replace method in Java Map

There are two overloaded replace methods

1. V replace(K key, V value)

Replaces the entry for the specified key only if it is currently mapped to some value.

Paramters are-

  • key- The specified key for which value has to be replaced
  • value- New value to be associated with the specified key

Method returns the previous value if the key is mapped to a value. Returns null if key is not associated with any value, returns null if associated values is null for the key.

2. boolean replace(K key, V oldValue, V newValue)

Replaces the oldValue with newValue for the specified key only if the key is currently mapped to the oldValue.

  • key- Specified key for which value has to be changed
  • oldValue- Value expected to be associated with the specified key
  • newValue- Value that replaces the oldValue

Method returns true if the value was replaced, false otherwise.

replace() method Java examples

In this example we'll use replace(K key, V value) variant.

import java.util.HashMap;
import java.util.Map;

public class ReplaceDemo {
  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    String prevValue = cityMap.replace("3", "Chennai");
    System.out.println("Value that is replaced " + prevValue);
    
    prevValue = cityMap.replace("5", "Mumbai");
    System.out.println("Value that is replaced " + prevValue);
    
    System.out.println("*** Map After replacement ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Value that is replaced Mumbai
Value that is replaced null
*** Map After replacement ***
{1=New York City, 2=New Delhi, 3=Chennai, 4=Berlin}

When "3" is passed as key in the replace() method the passed value replaces the previous value. In this case replace() method returns previous value associated with the key.

When "5" is passed as key there is no change in the Map as the key is not present in the HashMap. In this case replace() method returns null.

In this example we'll use replace(K key, V oldValue, V newValue) variant.

public class ReplaceDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    boolean isReplaced = cityMap.replace("3", "Mumbai", "Chennai");
    System.out.println("Is value replaced " + isReplaced);
    
    isReplaced = cityMap.replace("4", "Mumbai", "Madrid");
    System.out.println("Is value replaced " + isReplaced);
    
    System.out.println("*** Map After replacement ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Is value replaced true
Is value replaced false
*** Map After replacement ***
{1=New York City, 2=New Delhi, 3=Chennai, 4=Berlin}

First time value is replaced because key "3" was mapped with "Mumbai" initially. In this case replace() method returns true.

Second time there is no replacement because key "4" is there but it is not associated with "Mumbai". In this case replace() method returns false.

That's all for this topic Java Map replace() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Entry From HashMap in Java
  2. Java Map putIfAbsent() With Examples
  3. How HashMap Works Internally in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Difference Between Comparable and Comparator in Java

You may also like-

  1. How to Convert Array to ArrayList in Java
  2. Java Phaser With Examples
  3. Java Abstract Class and Abstract Method
  4. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  5. Convert double to int in Java
  6. Spring Setter Based Dependency Injection
  7. BeanFactoryAware Interface in Spring Framework
  8. FormGroup in Angular With Examples

Wednesday, October 19, 2022

How to Remove Entry From HashMap in Java

In this post we'll see how to remove an entry (key, value pair) from Map. Options you have are as given below-

  1. Using remove method- remove(Object key) provided by Map. See Example
  2. Using another remove method variant- remove(Object key, Object value) provided by Map. See Example
  3. Using remove() method provided by iterator. See Example
  4. Using removeIf() method. See Example

So, let's see when to use which method and why.

Removing entry from HashMap using remove(Object key) method

If you know the key for the entry which has to be removed, it is convenient to use remove(Object key) method rather than iterating the Map and then use iterator.remove() to remove the entry. This method returns the value which was associated with the removed key or null if the map contained no mapping for the key.

Here is an example with the map of cities where we'll try to remove Map.entry by passing one of the key.

import java.util.HashMap;
import java.util.Map;

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    cityMap.remove("4");
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai}

As you can see the entry with key as "4" is removed from the HashMap.

Removing entry from HashMap using remove(Object key, Object value) method

This is another overloaded remove() method in Map which makes removing an entry more restrictive. This method removes the entry for the specified key only if it is currently mapped to the specified value.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    cityMap.remove("4", "Berlin");
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai}

Since the passed key "4" is mapped to the specified value "Berlin" so entry is removed.

If you give a value that is not mapped with any key no entry is removed. For example, if you try cityMap.remove("4", "London"); HashMap will have no change.

Using iterator's remove() method

If you don't know the key before hand and iterating the Map to find the entry that has to be removed then using remove() method of the Iterator is a safe bet.

If you have to iterate a HashMap then you need to get a collection view of the Map. The iterators returned by HashMap's "collection view methods" are fail-fast: if the Map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Here is an example where remove() method of the Map is used to remove an entry (Structural modification) rather than using the remove() method of the iterator. This operation results in ConcurrentModificationException being thrown.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
    while(itr.hasNext()) {
      String key = itr.next().getKey();
      if(key.equals("2")) {
        cityMap.remove(key);
      }
    }

    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1597)
	at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1630)
	at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1628)
	at com.netjstech.collections.RemoveEntryDemo.main(RemoveEntryDemo.java:23)

Correct way to remove an entry from a Map while iterating it is to use iterator's remove() method.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
    while(itr.hasNext()) {
      if(itr.next().getKey().equals("2")) {
        itr.remove();
      }
    }

    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 3=Mumbai, 4=Berlin}

Using removeIf() method

removeIf() method is in Collection interface, since Map doesn't implement Collection so removeIf() method is not directly accessible in HashMap but after getting the Collection view of a Map removeIf() method can be used.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    cityMap.entrySet().removeIf(entry -> entry.getKey().equals("2"));


    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 3=Mumbai, 4=Berlin}
If you have a collection view of values then
cityMap.values().removeIf(v -> v.equals("Mumbai"));
Same way if you have a collection view of keys
cityMap.keySet().removeIf(k -> k.equals("2"));

That's all for this topic How to Remove Entry From HashMap in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map putIfAbsent() With Examples
  2. Java Map containsValue() - Check if Value Exists in Map
  3. How to Sort a HashMap in Java
  4. How LinkedList Class Works Internally in Java
  5. How to Sort Elements in Different Order in TreeSet

You may also like-

  1. Difference Between HashMap And ConcurrentHashMap in Java
  2. CompletableFuture in Java With Examples
  3. super Keyword in Java With Examples
  4. strictfp in Java
  5. Angular Application Bootstrap Process
  6. ServiceLocatorFactoryBean in Spring
  7. Spring @Async @EnableAsync Annotations - Asynchronous Method Support
  8. Python Conditional Statement - if, elif, else Statements