In this tutorial, we will learn ‘How to print HashSet elements’ in Java with some examples. It’s a very important concept in java or real word application developed using java.
HashSet:
-HashSet class is used to create a collection. A collection is an object that represents group of object.
-HashSet does not allow duplicate elements.
-HashSet allows null values. And it supports both homogeneous and heterogeneous elements.
-In HashSet we add/ insert element using add() method.
-It is an implementation of hashing technique with array representation. So insertion order is not preserved. It stores the elements according hash code based order.
-In HashSet elements are stored according to the following:
There are 3 ways to print HashSet elements:
- Using reference variable(Directly by name): We can directly print HashSet elements using HashSet object reference variable. It will print complete HashSet element.
Import java.util.*; Class HashSetDemo { Public static void main(String args[]) { HashSet<Character> hs = new HashSet<>(); hs.add(‘a’); hs.add(‘p’); hs.add(‘b’); System.out.println(hs); } }
- Using Iterator() method: It is used iterate elements of a collection. It will print element one by one form the collection. By using this method we can perform both read & remove operations.
Iterator it = hs.iterator(); while(it.hashNext()) { System.out.println(hs.next()); }
- Using Enhanced for loop: It is also used to print element one by one from the collection. It is introduced since JDK 1.5 version.
for(Object o : hs) { System.out.println(o); }