1.Basic java example program to check particular element is exists in hashset
  • boolean contains(Object o)   This method Returns true if this set contains the specified element

  1. package com.checkelementhashset;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Iterator;
  5.  
  6. public class HashsetExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10. //create object of HashSet
  11.  HashSet<Integer> hashSet = new HashSet();
  12.        
  13.  //add elements to HashSet object
  14.  hashSet.add(1);
  15.  hashSet.add(2);
  16.  hashSet.add(3);
  17.  hashSet.add(4);
  18.  hashSet.add(5);
  19.      
  20.  /*
  21.  To check whether a particular value exists in HashSetwe need to use
  22.   boolean contains(Object value) method of HashSet class.
  23.  this method returns true if the HashSet contains the value, otherwise returns false.
  24.  */
  25.        
  26.         boolean isExists = hashSet.contains(5);
  27.         System.out.println("5 exists in HashSet ? : " + isExists);    
  28.  

  29.  
  30. Iterator it=hashSet.iterator();
  31.              
  32. while(it.hasNext()){
  33. System.out.println(it.next());
  34.                      
  35. }   
  36.  
  37. }
  38.  
  39. }
     



Output:

  1. 3 exists in HashSet ? : true
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu