Learn Java , Selenium

HashSet – In Java

				
					import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Program3 {

	public static void main(String[] args) {

		HashSet<String> country = new HashSet<String>();
		country.add("India");
		country.add("USA");
		country.add("China");
		country.add("Russia");
		System.out.println(country);

	}
}

				
			

Output –

[USA, China, India, Russia]

Note: The order may change every time you run the program. That’s because HashSet does not maintain insertion order.


🔍 What is a HashSet?

  • HashSet is a collection of unique elements — duplicates are not allowed.

  • It is part of Java’s Collection Framework.

  • It is unordered — the elements may not appear in the order you added them.

💡 Key Features:

FeatureDescription
No DuplicatesAutomatically ignores duplicate entries
Fast LookupUses hashing for quick access
No Order GuaranteeElements can appear in any order

❗ Example: Adding Duplicate

 
           country.add(“India”); // Duplicate
           System.out.println(country); // “India” will not be added again

🔁 Looping Through a HashSet:

 
for (String c : country) {
System.out.println("Country: " + c);
}

📦 When to Use HashSet:

  • When you need to store unique values.

  • When you don’t care about the order.

  • Useful for things like tags, sets of IDs, or filtering duplicates.

 

 

Scroll to Top