Monday, July 14, 2025

Difference between HashMap, LinkedHashMap and TreeMap in Java with Example

Hello guys, if you are wondering what is difference between HashMap, TreeMap, and LinkedHashMap in Java and when to use them then you are at the right place. In past, I have shared frequently asked HashMap Interview questions and ConcurrentHashMAp Interview questions and today, I Will answer this question in detail. The java.util.Map is one of the most important interfaces from the Java Collection Framework.  It provides hash table data structure functionality by its implementations like HashMap, Hashtable, LinkedHashMap, and a little bit of sorting with the TreeMap. So if you are looking to store key-value pairs in the Java program,  you have a wide range of choices available depending upon your requirement. The main difference between LinkedHashMap, TreeMap, and HashMap comes in their internal implementation and specific features, which a Java programmer should know to use them effectively. 

How to get Key From Value in Hashtable, HashMap in Java? Example

It's not easy to get key from the value in Hashtable or HashMap, as compared to getting value from key because HashMap or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. in fact, Map allows the same value to be mapped to multiple keys inside HashMap, Hashtable, or any other Map implementation. What you have in your kitty is Hashtable.containsValue(String value) or Hashtable.containsKey(String key) to check whether key or value exists in HashMap or not, but sometimes we want to retrieve a value from Map corresponding to any key and there is no API method to do in Map.

Difference between HashMap and IdentityHashMap in Java? Example

Hello guys, if you are wondering what is differnece between an HashMap and IdentiyHashMap in Java then you are at right place. IdentityHashMap in Java was added in Java 1.4 but still, it's one of those lesser-known classes in Java. The main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing objects unlike other implementations of Map e.g. HashMap. Instead, IdentityHashMap uses the equality operator "=="  to compare keys and values in Java which makes it faster compared to HashMap and suitable where you need reference equality check and instead of logical equality.

What is difference between ArrayList and ArrayList<?> in Java?- Raw Type vs Wildcard Example Tutorial

One of my readers asked me about the difference between ArrayList vs ArrayList< in Java?>, which was actually asked to him in a recent Java development interview. The key difference between them is that ArrayList is not using Generics while ArrayList is a generic ArrayList but they look very similar. If a method accepts ArrayList or ArrayList<?> as a parameter then it can accept any type of ArrayList like ArrayList of String, Integer, Date, or Object, but if you look closely you will find that one is raw type while the other is using an unbounded wildcard. What difference that could make? Well, that makes a significant difference because ArrayList with raw type is not type-safe but ArrayList<?> with the unbounded wildcard is type-safe.

How to Filter Stream and Collections in Java 8? Example Tutorial

Java 8 provides excellent features to support the filtering of elements in Java Collections. Prior to Java 8, the only better way to filter elements is by using a foreach loop or iterating over Collection using the Iterator and selecting the required object, leaving out rest. Though that approach work, it was very difficult to run them in parallel and take advantage of multiple CPUs available in modern-day servers. Java 8 provides Streams, which not only makes it easy to run any operation parallel but also supports lazy loading and lazy evaluation, which means as soon as the filtering condition is satisfied, it stooped doing work, doesn't matter how many objects the collection contains.

Top 25 Java Collection Framework Interview Questions Answers for Freshers and Experienced Programmers

Interview questions from the Collection package or framework are most common in any Core Java Interview yet a tricky one. Together Collection and multithreading make any Java interview tough to crack and having a good understanding of Collection and threads will help you to excel in Java interviews. I thought about writing interview questions on the Java collection framework and important classes like ArrayList, HashMap, Hashtable, and newly added concurrent collections e.g. ConcurrentHashMap when I first wrote 10 multi-threading Interview questions but somehow this article got delayed. Though I have shared several questions individually in between.

How to Convert Collection to String in Java - Spring Framework Example

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma-separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through the loop and create a big String where individual String are separated by a delimiter, you still need to handle cases like the last element should not have a delimiter or at a bare minimum, you need to test that code.

How does Java HashMap or LinkedHahsMap handles collisions?

Prior to Java 8, HashMap and all other hash table based Map implementation classes in Java handle collision by chaining, i.e. they use linked list to store map entries which ended in the same bucket due to a collision. If a key end up in the same bucket location where entry is already stored then this entry is just added at the head of the linked list there. In the worst case this degrades the performance of the get() method of HashMap to O(n) from O(1). In order to address this issue in the case of frequent HashMap collisions, Java8 has started using a balanced tree instead of a linked list for storing collided entries. This also means that in the worst case you will get a performance boost from O(n) to O(log n).

Difference between HashMap and HashSet in Java

HashMap vs HashSet is the most frequently asked question during any core java interview and the interview is not said completed until they will not cover the Collection Framework and multi-threading interview and collections are uncompleted without Covering Hash Set and HashMap.
Both HashMap and HashSet are part of the collection framework which allows us to work with a collection of objects. Collection Framework has its own interfaces and implementation classes. Basically, a collection is divided into Set Interface, List, and Queue Interfaces.

Difference between EnumMap and HashMap in Java? Example

HashMap vs EnumMap in Java
What is the difference between EnumMap and HashMap in Java is the latest Java collection interview question which has been asked to a couple of my friends? This is one of the tricky Java questions, especially if you are not very much familiar with EnumMap in Java, which is not uncommon, given you can use it with only Enum keys. The main difference between EnumMap and HashMap is that EnumMap is a specialized Map implementation exclusively for Enum as key. Using Enum as a key allows doing some implementation level optimization for high performance which is generally not possible with other objects as key.

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

ConcurrentHashMap vs Hashtable vs Synchronized Map
Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

How to Iterate through ConcurrentHashMap and print all keys and values in Java? Example

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you do that? This is a common, day-to-day programming task for Java programmers and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choices like you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key-value pairs while printing if needed.

Saturday, July 12, 2025

Enhanced For Loop Example and Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of the for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing, and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is a basic requirement of using a Collection in the for-each loop, not everyone can answer.

JUnit4 Annotations : Test Examples and Tutorial

JUnit4 Annotations are a single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations creating and running a JUnit test becomes easier and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of annotations used on this version and how to use them while writing tests. In this
Junit tutorial we will not only understand the meaning of those annotations but also we will see examples of JUnit4 annotations. By the way, this is my first post in unit testing but if you are new here than you may like post 10 tips to write better code comments and 10 Object-oriented design principles for Programmer as well.

JUnit Testing Tips - Constructor is Called Before Executing Test Methods? Example

Even though almost all Java programmers either use JUnit or TestNG for their unit testing need along with some mock object generation libraries e.g. Mockito, but not everyone spends time and effort to learn subtle details of these testing libraries, at least not in proportion to any popular framework like Spring or Hibernate. In this blog post, I am sharing one of such detail, which has puzzled me a couple of years ago. At that time, though I had been using JUnit for a significant time, I wasn't aware that code written inside the constructor of the Test class is executed before each test method.