×

Java Programs

Java Practice

Java program to compare TreeSet collections

Given two TreeSet collections, we have to compare them.
Submitted by Nidhi, on June 04, 2022

Problem statement

In this program, we will create three TreeSet collections with integer elements. Then we will compare TreeSet collections using the equals() method and print the appropriate message.

Java program to compare TreeSet collections

The source code to compare TreeSet collections is given below. The given program is compiled and executed successfully.

// Java program to compare TreeSet collections

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String args[]) {
    TreeSet < Integer > tree1 = new TreeSet < Integer > ();
    TreeSet < Integer > tree2 = new TreeSet < Integer > ();
    TreeSet < Integer > tree3 = new TreeSet < Integer > ();

    tree1.add(10);
    tree1.add(20);
    tree1.add(30);
    tree1.add(40);
    tree1.add(50);

    tree2.add(10);
    tree2.add(60);
    tree2.add(30);
    tree2.add(40);
    tree2.add(50);

    tree3.add(10);
    tree3.add(20);
    tree3.add(30);
    tree3.add(40);
    tree3.add(50);

    if (tree1.equals(tree2))
      System.out.println("TreeSets tree1 and tree2 have similar elements.");
    else
      System.out.println("TreeSets tree1 and tree2 have not similar elements.");

    if (tree1.equals(tree3))
      System.out.println("TreeSets tree1 and tree3 have similar elements.");
    else
      System.out.println("TreeSets tree1 and tree3 have not similar elements.");
  }
}

Output

TreeSets tree1 and tree2 have not similar elements.
TreeSets tree1 and tree3 have similar elements.

Explanation

In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. Here, we created three TreeSet collection tree1, tree2, and tree3. Then we added elements using add() method. After that, we compared TreeSets using the equals() method and printed the appropriate message.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.