Java Program to Create Set of Pairs Using HashSet
HashSet in Java:
HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection point in Java.
private static final Object PR = new Object();
private HashMap<E,Obj> map = new HashMap<>();
public boolean add(E e) {
return map.put(e, PR)==null;
}
This is how the add() strategy in a HashSet seems. When a component is added to the HashSet, it is put away in a HashMap inside, kept up with by it. The key is the article we include, and worth is a spurious item. HashSet is beneficial when we need an information structure that contains no copy values.
Characteristics of HashSet in Java:
- HashSet inside utilises HashMap to store objects.
- It doesn't contain copy components. All components in a HashSet are exceptional.
- It doesn't keep up with the inclusion request. At the point when we emphasise a HashSet, the components can be gotten to in any request.
- It permits invalid qualities to be put away in it.
- The default beginning limit is 16.
- It isn't synchronised (i.e.) on the off chance that different strings access the hash set simultaneously and one of the strings changes the hash set, it should be remotely synchronised.
Initial Capacity and Load Factor of HashSet:
Before diving deep into HashSet, we should initially comprehend two significant terms, introductory limit and burden factor. These variables decide the underlying size of the HashSet and when to separately build the size.
Initial Capacity:
HashSet inside utilises HashMap, and the underlying limit determines the underlying container size of the HashMap. The default beginning limit of HashSet is 16.
Load Factor:
The heap factor is an edge that chooses when the size of the HashSet must be expanded. The default load factor is 0.75 (i.e.), and the scope of the inner HashMap will be extended once it is 75% filled.
Different Ways to Create HashSet in Java:
HashSet in Java can be made in numerous ways, incorporating making a HashSet with a default limit, making a HashSet with starting limit, and making a HashSet with starting limit and burden factor.
Example:
We should consider a HashSet with an underlying limit of 20 and a heap variable of 0.75. The size of the inside HashMap will be expanded when it has 15 components in it.
HashSet <T> ()
Makes a void HashSet with an underlying limit of 16 and a heap component of 0.75.
HashSet <T> h = new HashSet <T>();
HashSet <T> (int initialCapacity)
Makes a void HashSet with the given initial capacity and a heap element of 0.75
HashSet <T> h = new HashSet <T>(int initialCapacity);
HashSet <T> (int initialCapacity, float loadFactor)
Makes a void HashSet with the given initial capacity and load Factor.
HashSet <T> h = new HashSet <T>(int initialCapacity, float loadFactor);
HashSet <T> (Collection assortment)
Makes a HashSet containing every one of the components of the given assortment.
HashSet <T> hs = new HashSet <T>(Collection collection);
Operations on HashSet:
HashSet gives a few tasks that are utilised to add, eliminate and emphasise its components.
Adding Elements:
HashSet gives add() and addAll() techniques that are utilised to embed components to it.
add():
The add() technique embeds the given component to the HashSet if it is absent. It returns valid if the element is added and bogus, assuming it is now in the HashSet.
Syntax:
boolean add(elements);
Example:
//simple program to add elements to the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > h = new HashSet < > ();
//adding the element to the HashSet and printing them
System.out.println("here, we are adding the element 10: " + h.add(10));
System.out.println("here, we are adding the element 20: " + h.add(20));
System.out.println("here, we are adding the element 10 again: " + h.add(10));
//printing the elements of the HashSet
System.out.println("HashSet elements are: " + h);
}
}
Output:
Here, we are adding the element 10: true
Here, we are adding the element 20: true
Here, we are adding the element 10 again: false
HashSet elements are: [10, 20]
Explanation:
We have added a duplicate element 10 to the HashSet in the above example. But in the HashSet, we cannot add any duplicate elements, so we have to get the output as false.
addAll():
The addAll() strategy embeds every one of the components of the given assortment into the HashSet. It returns valid, assuming the components of the assortment are added effectively, which is generally misleading. The addAll() strategy can be utilised to perform the association of two sets.
Syntax:
boolean addAll(Collection or set of elements);
Example:
//simple program to add elements to the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40));
HashSet < Integer > j = new HashSet < > (Arrays.asList(10, 20, 50));
System.out.print("Union of the given sets " + i + " and " + j + " is ");
i.addAll(j);
//here, we are printing the union of both sets
System.out.println(i);
}
}
Output:
Union of the given sets [10, 20, 30, 40] and [10, 20, 50] is [10, 20, 30, 40, 50]
Removing Elements:
HashSet gives eliminate(), removeAll(), and removeIf() strategies that are utilized to eliminate components from it.
remove():
The remove() strategy eliminates the given component from the HashSet. It returns true, assuming the component is available in it, generally false.
Syntax:
boolean remove(Object or element);
Example:
//simple program to remove elements to the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40, 50));
//removing the element to the HashSet and printing the remaining elements
System.out.println("here, we are removing the element 10: " + h.remove(10));
System.out.println("here, we are removing the element 20: " + h.remove(20));
System.out.println("here, we are removing the element 10 again:"+ h.remove(10));
//printing the elements of the HashSet
System.out.println("HashSet elements after performing remove operation: " + h);
}
}
Output:
Here, we are removing element 10: true
Here, we are removing element 20: true
Here, we are removing element 60: false
HashSet elements after performing the remove operation: [30, 40, 50]
removeAll():
The removeAll() technique eliminates every one of the components present in the given assortment from the HashSet. It returns valid, assuming that the HashSet is changed, which is generally misleading. The removeAll() technique can be utilised to track down the distinction between two sets.
Syntax:
boolean remove(Collection or set of elements);
Example:
//simple program to remove elements to the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40));
HashSet < Integer > j = new HashSet < > (Arrays.asList(10, 20, 50));
System.out.print("Difference of the given sets " + i + " and " + j + " is ");
i.removeAll(j);
//here, we are printing the difference between both sets
System.out.println(i);
}
}
Output:
Difference of the given sets [10, 20, 30, 40] and [10, 20, 50] is [30, 40]
removeIf():
The removeIf() technique eliminates all the HashSet components that match the given Predicate.
The predicate is a useful connection point in Java that acknowledges a piece of solitary information and can return a boolean worth.
Syntax:
boolean removeIf(Predicate);
Example:
//simple program to remove elements of the set using the conditions
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40, 50));
h.removeIf(x -> x % 2 == 0);
System.out.println("Elements after removing even values: " + h);
}
}
Output:
Elements after removing even values: [10, 30, 50]
retainAll:
The retainAll() holds every one of the components from a HashSet that are absent in the given assortment. The retainAll() technique can be utilised to perform the intersection point of two sets.
The intersection point of two sets, An and B, is the arrangement of all items that are individual from both A and B.
Syntax:
boolean retainAll(Collection c);
Example:
//simple program to retain elements from the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40));
HashSet < Integer > j = new HashSet < > (Arrays.asList(10, 20, 50));
System.out.print("Intersection of the given sets " + i + " and " + j + " is ");
i.retainAll(j);
//here, we are printing the Intersection of both sets
System.out.println(i);
}
}
Output:
Intersection of the given sets [10, 20, 30, 40] and [10, 20, 50] is [10, 20]
Finding Elements:
HashSet gives two technique, contains() and containsAll(), that is utilised to find, assuming a given component or components in an offered assortment is available in a HashSet separately.
Contains():
The contains() technique checks in the event that a given component is available in the HashSet. It returns valid assuming that the component is available, generally false.
Syntax:
boolean contains(Object or element);
Example:
//simple program to remove elements to the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40, 50));
//checking the element of the HashSet and printing the elements
System.out.println("here, we are checking the element 10 is present in the set or not: " + h.contains(10));
System.out.println("here, we are checking the element 70 is present in the set or not: " + h.contains(20));
}
}
Output:
Here, we are checking the element 10 is present in the set or not: true
Here, we are checking the element 70 is present in the set or not: false
containsAll():
The containsAll() technique checks assuming that every one of the components in the given assortment is available in the HashSet. It returns valid assuming that every one of the components is available, which is generally misleading. The containsAll() strategy can be utilised to check if a set is a subset of one more set.
A set B is a subset of one more set An on the off chance that all components of set B are components of set A.
Syntax:
boolean containsAll(Collection or set of elements);
Example:
//simple program to retain elements from the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > i = new HashSet < > (Arrays.asList(10, 20, 30, 40));
HashSet < Integer > j = new HashSet < > (Arrays.asList(10, 20));
System.out.println("Is " + j + "is the subset of " + i + ": " + i.containsAll(j));
}
}
Output:
Is [10, 20] is the subset of [10, 20, 20, 40] : true
Iterating through the HashSet:
HashSet gives the iterator() technique that can be utilized to repeat components of the HashSet. The components can likewise be iterated utilizing for and forEach.
Example:
//simple program to retain elements from the HashSet
import java.io.*; //here, we are importing the java.io package to our program
import java.util.*; //here, we are importing the java.util package to our program
import java.lang.*; //here, we are importing the java.lang package to our program
class H1 {
public static void main(String[] args) {
HashSet < Integer > h = new HashSet < > (Arrays.asList(10, 20, 30, 40, 50));
// here, we are using the for loop to iterate the HashSet
System.out.println("Iterating elements using for loop");
for (Integer value: h) {
System.out.println(value);
}
// here, we are using the for-each loop to iterate the HashSet
System.out.println("Iterating elements using forEach loop");
h.forEach(x -> System.out.println(x));
// // here, we are using the Iterator to iterate the HashSet
System.out.println("Iterating elements using iterator");
Iterator < Integer > iterator = h.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
Iterating elements using for loop
10
20
30
40
50
Iterating elements using for-Each loop
10
20
30
40
50
Iterating elements using an iterator
10
20
30
40
50
Problem statement: We need to find and print unique pairs among all given pairs.
and large, in the event that we need to find extraordinary numbers among every single given number, we just put all numbers in HashSet and print them. Allow us to consider an example representation to decipher the issue proclamation better. Assume we have three sets of customs they are (3, 5), (4, 5), (3, 5). Presently in the event that we put it in the set, the result will be.
Output: (3, 5), (4, 5), (3, 5)
We can create the set of pairs using the Syntax:
HashSet<Pair> set = new HashSet<>();
From the model, we can obviously see that copy matches are as yet present. This is on the grounds that for the set, Match is a similar sort of item and it can't separate between them. So to beat this issue we can simply create a series of records and upsides of Matches and store it in Set in the type of String and afterwards print it and you can get every unique pair.
Example:
//simple Java Program to Create a Set of Pairs using the HashSet
//here, we are importing required classes into our program
import java.io.*; //here, we are importing the java.io package to our program
import java.util.HashSet; //here, we are importing the java.util package to our //program
//here, we are declaring the Class 1
//here, we are declaring the Helper class for creating pairs
class Pair {
//here, we are declaring the Pair attributes
public int ind;
public int value;
//here, we are declaring the Constructor to initialize pair
public Pair(int ind, int value)
{
//here, This keyword refers to the current instance
this.ind = ind;
this.value = value;
}
}
//here, we are declaring the Class 2
//here, we are declaring the Main class
class Hs {
//here, we are declaring the Main driver method
public static void main(String[] args)
{
//here, we are Initializing an array of Pair
//here, we are declaring the Custom input elements
Pair arr[] = new Pair[4]; //here, we are declaring the pairs with some values
arr[0] = new Pair(2, 3); //here, we are declaring the pairs with (2,3) values
arr[1] = new Pair(3, 4); //here, we are declaring the pairs with (3,4) values
arr[2] = new Pair(5, 10); //here, we are declaring the pairs with (5,10) values
arr[3] = new Pair(3, 4); //here, we are declaring the pairs with (3,4) values
//here, we are Creating a HashSet by declaring an object of string type
HashSet<String> set = new HashSet<>();
//here, we are Adding pair in the set-in form of a string
for (int i = 0; i < 4; i++) //here, we are using the for loop to add multiple items
{
set.add(arr[i].ind + ", " + arr[i].value);
}
//here, we are Lastly iterating using the for each loop and
//here, we are printing the elements pairs using the For-each loop
//here, we are printing the output statement
System.out.println(“Printing the set of pairs after removing all the duplicates”);
for (String e: set) //using the For-each loop to print the HashSet elements
System.out.println("(" + e + ")");
}
}
Output:
Printing the set of pairs after removing all the duplicates:
(5, 10)
(2, 3)
(3, 4)