1.Basic java example program to remove element hashset
Output:
- boolean remove(Object o) . This method is used to remove element from hashset if it is present it returns true.
- package com.getSizehashset;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashsetExample{
- public static void main(String[] args) {
- //create object of HashSet
- HashSet<Integer> hashSet = new HashSet();
- //add elements to HashSet object
- hashSet.add(1);
- hashSet.add(2);
- hashSet.add(3);
- hashSet.add(4);
- hashSet.add(5);
- hashSet.add(6);
- hashSet.add(7);
- hashSet.add(8);
- System.out.println("Size of HashSet after addition : " + hashSet.size());
- System.out.println("Hashset contains");
- Iterator it=hashSet.iterator();
- while(it.hasNext()){
- System.out.println(it.next());
- }
- boolean isRemoved = hashSet.remove(6);
- System.out.println("Was 6 removed from HashSet ? " + isRemoved );
- System.out.println("HashSet after removal : " + hashSet);
- }
- }
Output:
- Size of HashSet after addition
- 8
- hashset contains
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- Was 6 removed from HashSet ?true
- HashSet after removal : [1, 2, 3, 4,5,7,8]
Bagikan
Remove specified element from Java HashSet example
4/
5
Oleh
Kris Kimcil