Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to Compare Two TreeMap Objects in Java?

  • Last Updated : 05 Aug, 2021

TreeMap class in java provides a way of storing key-value pairs in sorted order. The below example shows how to compare two TreeMap objects using the equals() method. It compares two TreeMap objects and returns true if both of the maps have the same mappings else returns false.

Syntax:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

boolean equals(Object o)

Return: It returns true if both the maps are equal else returns false.

Java




// Java program to Compare Two TreeMap Objects
import java.io.*;
import java.util.ArrayList;
import java.util.TreeMap;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Creating first TreeMap
        TreeMap<Integer, String> Office1
            = new TreeMap<Integer, String>();
 
        Office1.put(1, "Mumbai");
        Office1.put(2, "Delhi");
 
        // Creating second TreeMap
        TreeMap<Integer, String> Office2
            = new TreeMap<Integer, String>();
 
        Office2.put(1, "Mumbai");
        Office2.put(2, "Delhi");
 
        // equals compares two TreeMap objects and
        // returns true if both of the maps have the same
        // mappings.
        System.out.println(Office1.equals(Office2));
 
        // add new mapping to second TreeMap
        Office2.put(3, "Goa");
 
        // this will return false as both TreeMap objects do
        // not contain same mappings
        System.out.println(Office1.equals(Office2));
    }
}
Output
true
false

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :