ADVERTISEMENT
ADVERTISEMENT

Java program to get the size of a HashSet Collection

Given a HashSet collection, we have to get the size of it.
Submitted by Nidhi, on May 10, 2022

Problem Solution:

In this program, we will create three sets using the HashSet collection to store integer elements. Then we will count the total number of elements of sets using the size() method.

Program/Source Code:

The source code to get the size of a HashSet Collection is given below. The given program is compiled and executed successfully.

// Java program to get the size of a 
// HashSet Collection

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashSet < Integer > nums1 = new HashSet();
    HashSet < Integer > nums2 = new HashSet();
    HashSet < Integer > nums3 = new HashSet();

    nums1.add(1);
    nums1.add(2);
    nums1.add(3);
    nums1.add(4);
    nums1.add(5);
    nums1.add(6);

    nums2.add(1);
    nums2.add(2);
    nums2.add(3);
    nums2.add(4);

    nums3.add(10);
    nums3.add(20);
    nums3.add(30);

    System.out.println("The size of nums1 set is: " + nums1.size());
    System.out.println("The size of nums2 set is: " + nums2.size());
    System.out.println("The size of nums3 set is: " + nums3.size());
  }
}

Output:

The size of nums1 set is: 6
The size of nums2 set is: 4
The size of nums3 set is: 3

Explanation:

In the above program, we imported the "java.util.*" package to use the HashSet collection. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. Here, we created three sets nums1, nums2, nums3 to store integer data elements using HashSet collection. Then we get the size of all sets using the size() method and printed the result.

Java HashSet Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.