Java HashSet

The HashSet implements the Set interface. Every item is unique in a HashSet. It is a part of the java.util package i.e., you need to import the java.util.HashSet package.

Let us see some LinkedList operation/ methods with examples:

  • Create a HashSet
  • Size of a Hashset
  • Loop through the HashSet
  • Remove an item from a HashSet
  • Check if an item exists in a HashSet

Let us first see how to create a HashSet in Java:

Create a HashSet

To create a HashSet, set the type in angular braces i.e., use the wrapper class. For example, for creating a HashSet with string elements, use <String>:

Let us now see an example and create a HashSet in Java with string elements:

Output

Size of HashSet

To get the size of HashSet i.e., how many elements does it have, use the size() method. Let us see an example:

Output

Loop through the HashSet

Use the for-each loop to loop through the ArrayList in Java. Let us see an example:

Output

Remove an item from a HashSet

To remove an element from a HashSet, use the remove() method. Set the element you want to remove as a parameter of the remove () method. For example, to remove the element “Football”, set it as:

Let us now see an example of removing an element from a HashSet in Java:

Output

Check if an item exists in a HashSet

The contains() method is used in a HashSet to check if an item exists. Let us see an example:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java ArrayList
Java HashMap
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading