How to Compare Two TreeMap Objects in Java?
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
// 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
Please Login to comment...