VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-create-set-of-pairs-using-hashset/

⇱ Java Program to Create Set of Pairs Using HashSet - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Create Set of Pairs Using HashSet

Last Updated : 23 Jul, 2025

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


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.

Comment
Article Tags: