Senin, 14 Maret 2016

Remove specified element from Java HashSet example

1.Basic java example program to remove element hashset
  • boolean remove(Object o) .   This method is used to remove element from hashset if it is present it returns true.

  1. package com.getSizehashset;
  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.  hashSet.add(6);
  20.  hashSet.add(7);
  21.  hashSet.add(8);
  22.  
  23. System.out.println("Size of HashSet after addition : " + hashSet.size());
  24.  
  25. System.out.println("Hashset contains");
  26.  
  27. Iterator it=hashSet.iterator();
  28.              
  29. while(it.hasNext()){
  30. System.out.println(it.next());
  31.                      
  32. }   
  33.  
  34. boolean isRemoved = hashSet.remove(6);
  35. System.out.println("Was 6 removed from HashSet ? " + isRemoved );
  36.  
  37. System.out.println("HashSet after removal : " + hashSet);
  38. }
  39.  
  40. }
     


Output:

  1. Size of HashSet after addition
  2. 8
  3. hashset contains
  4. 1
  5. 2
  6. 3
  7. 4
  8. 6
  9. 7
  10. 8
  11. Was 6 removed from HashSet ?true
  12. HashSet after removal : [1, 2, 3, 4,5,7,8]

Bagikan

Jangan lewatkan

Remove specified element from Java HashSet example
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.