Java Set size() example

In this guide, you will learn about the Set size() method in Java programming and how to use it with an example.

1. Set size() Method Overview


The size() method of the Java Set interface returns the number of elements in the set.


int numberOfElements = set.size();


- None.

Key Points:

- The method returns the count of elements present in the set.

- If the Set is empty, the method returns 0.

- The size returned accounts for the unique elements in the Set since a set does not allow duplicate elements.

2. Set size() Method Example

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

public class SetSizeExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();

        // Check the size of an empty set
        System.out.println("Size of empty set: " + fruits.size());  // 0

        // Adding some elements to the set

        // Check the size after adding elements
        System.out.println("Size after adding three fruits: " + fruits.size());  // 3

        // Adding duplicate elements

        // Check the size after adding duplicate elements
        System.out.println("Size after adding duplicate fruits: " + fruits.size());  // 3


Size of empty set: 0
Size after adding three fruits: 3
Size after adding duplicate fruits: 3


In this example:

1. We create a HashSet of fruits and initially check its size, which is 0 since it's empty.

2. We add three elements: "Apple", "Banana", and "Cherry" to the set and then check its size, which returns 3.

3. Next, we add two duplicate elements: "Apple" and "Banana". Since a set does not allow duplicate elements, these additions do not increase the size of the set. Thus, checking the size again returns 3.

The size() method is handy when you want to quickly assess the number of unique elements in a set. It provides a clear indication of the set's capacity without the need for iterating over its elements.

Related Java Set interface methods

Java Set add() example
Java Set contains() example
Java Set isEmpty() example
Java Set remove() example
Java Set size() example