Java Set size() Method Tutorial

In this section, we will learn what the Set size() method is and how to use it in Java.

What is Java Set size() Method?

The Java Set size() method is used to get the current number of elements in a Set object.

Java Set size() Method Syntax:

int size()

size() Method Parameters:

The method does not take an argument.

size() Method Return Value:

The return value of this method is of type Integer and is equal to the number of elements the target Set object has.

size() Method Exceptions:

The method does not throw an exception.

Example: using Set size() method

import java.util.Set;
import java.util.HashSet; 
public class Main {

    public static void main(String[] args){
      Set<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      set.add(5);
      set.add(6);
      set.add(7);

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

Output:

The size of the set is: 7
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies