HashSet In Java
--
Hashset basic example in java
Introduction:
A HashSet is a collection of items where every item is unique, and it is found in the java.util
package:
Example
Create a HashSet object called cars that will store strings:
import java.util.HashSet; // Import the HashSet class
HashSet<String> cars = new HashSet<String>();
Add Items
The HashSet
class has many useful methods. For example, to add items to it, use the add()
method
Program 1:adding items in hashset and printing it.
CODE:
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> Cricket = new HashSet<String>();//deaclaration of hashmap
Cricket.add(“Sachin”);
Cricket.add(“Virat”);
Cricket.add(“AB”);
Cricket.add(“Smith”);
Cricket.add(“Raina”);
System.out.println(Cricket);
}
}
OUTPUT:
[AB, Smith, Raina, Sachin, Virat]
Check If an Item Exists
To check whether an item exists in a HashSet, use the contains()
method:
Program 2:check item exists or not.
CODE:
// Import the HashSet class
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> Cricket = new HashSet<String>();//deaclaration of hashmap
Cricket.add(“Sachin”);
Cricket.add(“Virat”);
Cricket.add(“AB”);
Cricket.add(“Smith”);
Cricket.add(“Raina”);
System.out.println(Cricket.contains(“Mazda”));//checking using cntains method
}
}
OUTPUT:
True
Remove an Item
To remove an item, use the remove()
method
Program 3:remove element
CODE:
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> Cricket= new HashSet<String>();//deaclaration of hashmap
Cricket.add(“Sachin”);
Cricket.add(“Virat”);
Cricket.add(“AB”);
Cricket.add(“Smith”);
Cricket.add(“Raina”);
Cricket.remove(“Sachin”);
System.out.println(Cricket);
}
}
OUTPUT:
[AB, Smith, Raina, Virat]
Clear Method:
To remove all items, use the clear()
method:
Program 4:remove all items using clear method
CODE:
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add(“Volvo”);
cars.add(“BMW”);
cars.add(“Ford”);
cars.add(“BMW”);
cars.add(“Mazda”);
cars.clear();
System.out.println(cars);
}
}
OUTPUT:
[]
HashSet Size
To find out how many items there are, use the size
method:
Program 5: To find out how many items there are, use the size
method:
CODE:
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> Cricketers = new HashSet<String>();
Cricketers.add(“Sachin”);
Cricketers.add(“Virat”);
Cricketers.add(“MSD”);
Cricketers.add(“Riyan”);
Cricketers.add(“yuzi”);
System.out.println(Cricketers.size());
}
}
OUTPUT:
4
Loop Through a HashSet
Loop through the items of an HashSet
with a for-each loop:
Program 6:Using for eachloop printing set
CODE:
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> Cricketers = new HashSet<String>();
Cricketers.add(“Sachin”);
Cricketers.add(“Virat”);
Cricketers.add(“MSD”);
Cricketers.add(“Riyan”);
Cricketers.add(“yuzi”);
for (String i :Cricketers ) {
System.out.println(i);
}
}
}
OUTPUT:
Sachin
Virat
MSD
Riyan
Yuzi
Other datatypes we can use
Items in an HashSet are actually objects. In the examples above, we created items (objects) of type “String”. Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer
. For other primitive types, use: Boolean
for boolean, Character
for char, Double
for double, etc:
HashSet<Integer> numbers
=
new
HashSet<Integer>();
HashSet<Character > numbers
=
new
HashSet<Character>();
Use a HashSet
that stores Integer
objects
Program 7:Integer types hashset
CODE:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet<Integer> numbers = new HashSet<Integer>();
// Add values to the set
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Show which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + “ was found in the set.”);
} else {
System.out.println(i + “ was not found in the set.”);
}
}
}
}
OUTPUT:
1 was not found in the set.
2 was not found in the set.
3 was not found in the set.
4 was found in the set.
5 was not found in the set.
6 was not found in the set.
7 was found in the set.
8 was found in the set.
9 was not found in the set.
10 was not found in the set.
Program 8:check wheather two set is equal or not.
CODE:
// Java code to illustrate the equals() method
import java.util.*;
public class Abstract_Set_Demo {
public static void main(String[] args)
{
// Creating an empty AbstractSet
AbstractSet<String>
abstract_set1 = new HashSet<String>();
AbstractSet<String>
abstract_set2 = new HashSet<String>();
// Adding elements to set
abstract_set1.add(“Somnath”);
abstract_set1.add(“4”);
//abstract_set1.add(“Sachin”);
abstract_set1.add(“Welcomes”);
abstract_set1.add(“You”);
// Adding elements to set
abstract_set2.add(“Somnath”);
abstract_set2.add(“4”);
//abstract_set2.add(“Sachin”);
abstract_set2.add(“Welcomes”);
abstract_set2.add(“You”);
// Displaying the first HashSet
System.out.println(“First Set: “
+ abstract_set1);
// Displaying the second HashSet
System.out.println(“Second Set: “
+ abstract_set2);
// Displaying the equality
System.out.println(“Equality: “
+ abstract_set1
.equals(abstract_set2));
}
}
OUTPUT:
First Set: [4, Somnath, You, Welcomes]Second Set: [4, Somnath, You, Welcomes]Equality: true
Java HashSet from another Collection
Using while loop iterating all element .we can use iterator method as well.
Program 9:iterating through while loop
CODE:
import java.util.*;
class HashSet4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add(“Ravi”);
list.add(“Vijay”);
list.add(“Ajay”);
HashSet<String> set=new HashSet(list);
set.add(“Gaurav”);
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
OUTPUT:
VijayRaviGauravAjayPROGRAM 10:Hashset iterator exampleCODE:
// Java code to illustrate iterator()
import java.util.*;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String args[])
{
// Creating an empty HashSet
HashSet<String> set = new HashSet<String>();
// Use add() method to add elements into the Set
set.add(“Welcome”);
set.add(“To”);
set.add(“America”);
set.add(“and “);
set.add(“Portugiz”);
// Displaying the HashSet
System.out.println(“HashSet: “ + set);
// Creating an iterator
Iterator value = set.iterator();
// Displaying the values after iterating through the set
System.out.println(“The iterator values are: “);
while (value.hasNext()) {//chacking upto the null
System.out.println(value.next());
}
}
}
OUTPUT:HashSet: [and, America, Welcome, To,portugiz]The iterator values are:andAmericaPortugizTo
Java HashSet Example: Book
Let’s see a HashSet example where we are adding books to set and printing all the book
Program 10:Accesing element using object and printing it .
CODE:
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,”Let us C”,”Yashwant Kanetkar”,”BPB”,8);
Book b2=new Book(102,”Data Communications & Networking”,”Forouzan”,”Mc Graw Hill”,4);
Book b3=new Book(103,”Operating System”,”Galvin”,”Wiley”,6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+” “+b.name+” “+b.author+” “+b.publisher+” “+b.quantity);
}
}
}
OUTPUT:
101 Let us C Yashwant Kanetkar BPB 8102 Data Communications & Networking Forouzan Mc Graw Hill 4103 Operating System Galvin Wiley 6
Note*: Book b created object and acessing all elements.
Using for loop
Note*:Hash stores unique values not to be repeated
Thank you.do read all method and practise more.any query please ask us.