Open In App

Java Program to Create Set of Pairs Using HashSet

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Problem statement: We need to find and print unique pairs among all given pairs.

Generally, if we have to find the unique numbers among all given numbers then we just put all numbers in HashSet and print them. Let us consider a sample illustration to interpret the problem statement better. Suppose we have three pairs be customly they are (3, 5), (4, 5), (3, 5). Now if we put it in the set then the output will be.

Output: (3, 5), (4, 5), (3, 5)

Note: But in the case of Pair, we can’t just write as shown below but if we try to put Pair in a set then it gives us the problem for illustration.

HashSet<Pair> set = new HashSet<>();

 From the example, we can clearly see that duplicate pairs are still present. This is because for the set, Pair is the same type of object and it can’t differentiate between them. So to overcome this problem we can just make a string of indexes and values of  Pairs and store it in Set in form of String and then print it and you can get all unique pairs.

Example

Java




// Java Program to Create Set of Pairs
// using HashSet
 
// Importing required classes
import java.io.*;
import java.util.HashSet;
 
// Class 1
// Helper class for creating pairs
class Pair {
 
    // Pair attributes
    public int index;
    public int value;
 
    // Constructor to initialize pair
    public Pair(int index, int value)
    {
        // This keyword refers to current instance
        this.index = index;
        this.value = value;
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Initializing an array of Pair
        // Custom input elements
        Pair arr[] = new Pair[4];
        arr[0] = new Pair(2, 3);
        arr[1] = new Pair(3, 4);
        arr[2] = new Pair(5, 10);
        arr[3] = new Pair(3, 4);
 
        // Creating a hashSet by
        // declaring object of string type
        HashSet<String> set = new HashSet<>();
 
        // Adding pair in set in form of string
        for (int i = 0; i < 4; i++) {
            set.add(arr[i].index + ", " + arr[i].value);
        }
 
        // Lastly iterating using for each loop and
        // printing the elements pairs
        for (String e : set)
            System.out.println("(" + e + ")");
    }
}


Output

(5, 10)
(2, 3)
(3, 4)

Output explanation:

So from the code and output, you can clearly see that duplicate pairs are deleted and we can get all unique pairs without overriding the hashCode() method and equals() method.



Last Updated : 03 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads