Collection -Set
Set interface includes all the methods of the Collection interface. Its because Collection is a super interface of List
- Set does not allow duplicate elements.
- Does not maintain insertion order
HashSet –Operations with Example
- Create a HashSet
- Adding elements
- Removing elements
- Changing elements
- Iterating through the HashSet
package com.example;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetExample {
public static void main(String[] args) {
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
System.out.println(" Hash set is"+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println("Iterator way loop print data "+itr.next());
}
//for each loop
for(String str : set){
System.out.println("For loop way print data "+str);
}
}
}
Comments
Post a Comment