How to check HashSet Empty Or not

To check Set/HashSet is empty or not we use isEmpty() method . HashSet isEmpty() method returns true if this set contains no elements.If you are new with java collection i will recommended to you read this A Guide to Collection in java . Let’s see this by code

import java.util.HashSet;
import java.util.Set;

public class IsEmpty {

public static void main(String[] args) {

Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
hs.add("javascript");
hs.add("mysql");

//print hashset
System.out.println("hashset = "+hs);

System.out.println(hs.isEmpty());

HashSet<String> hs2 = new HashSet<String>();

System.out.println(hs2.isEmpty());
}

}

Output:

hashset = [javascript, php, html, java, mysql]

false

true

A Guide To HashSet                                                                                                            Java Doc – HashSet

 

Leave a Reply

Your email address will not be published. Required fields are marked *

− 2 = 4