Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. set.size() / isEmpty() / iterator()

set.size() / isEmpty() / iterator()

Methods for getting the number of elements in a set, checking whether a set is empty, and iterating over all elements in order. Since sets do not support index-based access, use iterator() or an enhanced for loop to iterate over elements.

Syntax

// Returns the number of elements in the set.
set.size();

// Checks whether the set is empty.
set.isEmpty();

// Retrieves an iterator for the set.
Iterator<Type> it = set.iterator();

// Iterates over all elements using an enhanced for loop.
for (Type variable : set) { ... }

// Iterates over all elements using a lambda expression (Java 8+).
set.forEach(element -> process);

// Converts the set to an array.
set.toArray();

Method List

MethodDescription
size()Returns the number of elements in the set as an int.
isEmpty()Returns whether the set is empty as a boolean.
iterator()Returns an iterator for the set. Use it together with hasNext() and next().
forEach(Consumer)Executes a lambda expression for every element in the set (Java 8+).
toArray()Converts all elements in the set to an Object[] array and returns it.

Sample Code

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

Set<String> colors = new HashSet<>();
colors.add("red");
colors.add("green");
colors.add("blue");

// Check the size.
System.out.println(colors.size()); // Outputs "3".

// Check whether the set is empty.
System.out.println(colors.isEmpty()); // Outputs "false".

// Iterate over all elements using an iterator.
Iterator<String> it = colors.iterator();
while (it.hasNext()) {
    System.out.println(it.next()); // Each element is printed.
}

// Iterate over all elements using an enhanced for loop.
for (String color : colors) {
    System.out.println(color);
}

// Iterate using forEach and a lambda expression (Java 8+).
colors.forEach(color -> System.out.println(color));

// Convert to an array.
Object[] arr = colors.toArray();
System.out.println(arr.length); // Outputs "3".

Notes

size() returns the number of elements in the set. Unlike lists, sets do not support index-based access, so use an enhanced for loop, an iterator, or forEach() to iterate over elements.

Adding or removing elements while iterating with an iterator throws a ConcurrentModificationException. If you need to remove elements during iteration, use the iterator's remove() method.

For creating a set and using add, check, and remove operations, see 'new HashSet<>() / add() / contains() / remove()'.

If you find any errors or copyright issues, please .