Nov 11

How to iterate HashSet in java using iterator?

3)      Example to iterate HashSet in java

package javaexamples;import java.util.HashSet;import java.util.Iterator;

import java.util.Set;

 

public class IteratingHashSet {

public static void main(String[] args) {

Set<String> strings = new HashSet<String>();

strings.add(“HashSetElement1”);

strings.add(“HashSetElement2”);

strings.add(“HashSetElement3”);

System.out.println(“Elements of HashSet are printed below”);

Iterator<String> itr = strings.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

}

}

}

 

 

Output:

Elements of HashSet are printed belowHashSetElement4HashSetElement3HashSetElement1
Nov 11

How to find size of HashSet in java?

 2)      Example to find size of  HashSet  in java

package javaexamples;import java.util.HashSet;

import java.util.Set;

 

public class HashSetExample {

public static void main(String[] args) {

Set<String> strings = new HashSet<String>();

strings.add(“example1”);

strings.add(“example2”);

strings.add(“example3”);

System.out.println(“Initial size of HashSet is ” + strings.size());

strings.remove(“example1”);

System.out.println(“After removing object size of Hash Set is ” + strings.size());

 

}

 

}

Output

Initial size of HashSet is 3After removing object size of Hash Set is 2
Nov 11

How to create HashSet in Java?

1)   Example to create HashSet in java

package javaexamples; 

import java.util.HashSet;

import java.util.Set;

public class CreatingHashSet {

public static void main(String[] args) {

Set<Integer> set = new HashSet<Integer>();

set.add(1);

set.add(2);

set.add(3);

for (Integer integer : set) {

System.out.println(integer);

}

}

}

 

Output :

123