Skip to content
Related Articles

Related Articles

How to Compare Two TreeMap Objects in Java?
  • Last Updated : 28 Dec, 2020

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:

boolean equals(Object o)

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

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java proram 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));
    }
}

chevron_right


Output

true
false

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :