This example shows how to create a HashSet and adding elements to it in Java with an example.
Create HashSet in Java Example
package com.javaguides.collections.hashsetexamples; import java.util.HashSet; import java.util.Set; public class CreateHashSetExample { public static void main(String[] args) { // Creating a HashSet Set < String > daysOfWeek = new HashSet < > (); // Adding new elements to the HashSet daysOfWeek.add("Monday"); daysOfWeek.add("Tuesday"); daysOfWeek.add("Wednesday"); daysOfWeek.add("Thursday"); daysOfWeek.add("Friday"); daysOfWeek.add("Saturday"); daysOfWeek.add("Sunday"); // Adding duplicate elements will be ignored daysOfWeek.add("Monday"); System.out.println(daysOfWeek); } }
Output
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
Reference
Related Java HashSet Source Code Examples
- Creating a HashSet and Adding New Elements to It
- Java 8 forEach() Set Example
- Java Convert Array to Set
- Iterating over a HashSet using Iterator
- Iterate over HashSet in Java
- Remove Element from HashSet in Java
- Create HashSet in Java
Collection Framework
HashSet
Java
Comments
Post a Comment