iterate through hashset in java code example
Example 1: iterate hashmap java
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Example 2: set iteration java
import java.util.HashSet;
import java.util.Iterator;
class IterateHashSet{
public static void main(String[] args) {
HashSet<String> hset = new HashSet<String>();
hset.add("Chaitanya");
hset.add("Rahul");
Iterator<String> it = hset.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}