HashSet In Java

Introduction:

A HashSet is a collection of items where every item is unique, and it is found in the java.util package:

Add Items

The HashSet class has many useful methods. For example, to add items to it, use the add() method

[AB, Smith, Raina, Sachin, Virat]

Check If an Item Exists

To check whether an item exists in a HashSet, use the contains() method:

Remove an Item

To remove an item, use the remove() method

[AB, Smith, Raina, Virat]

HashSet Size

To find out how many items there are, use the size method:

Loop Through a HashSet

Loop through the items of an HashSet with a for-each loop:

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.

VijayRaviGauravAjayPROGRAM 10:Hashset iterator exampleCODE:
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

101 Let us C Yashwant Kanetkar BPB 8102 Data Communications & Networking Forouzan Mc Graw Hill 4103 Operating System Galvin Wiley 6

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store