educative.io

Educative

How to import HashSet in java?

import java.util.Set;

class HappyNumber {

      public static boolean find(int n) {
        Set<Integer> set = new HashSet<>();
        while(n != 1) {
            int sum = 0;
            while(n > 0) {
                int rem = n % 10;
                sum += rem * rem;
                n /= 10;
            }
            
            if(set.contains(sum)) return false;
            set.add(sum);
            n = sum;
        }
        return true;
    }    

  public static void main(String[] args) {
    System.out.println(HappyNumber.find(23));
    System.out.println(HappyNumber.find(12));
  }
}

It gives the below error:

main.java:6: error: cannot find symbol
        Set<Integer> set = new HashSet<>();
                               ^
  symbol:   class HashSet
  location: class HappyNumber
1 error

The above code doesn’t work. How does one import HashSet or other packages in java?

Hi @rohit3. Apologies for the very late answer. You have to import java.util.Set and java.util.HashSet.

Happy Learning :smiley: