Java HashSet forEach() Method

The HashSet.forEach() method in Java is used to perform the given action for each element of the HashSet until all elements have been processed or the action throws an exception.

Table of Contents

  1. Introduction
  2. forEach Method Syntax
  3. Examples
    • Printing Each Element of a HashSet
    • Modifying Each Element in a HashSet
  4. Conclusion

Introduction

The HashSet.forEach() method is a member of the HashSet class in Java. It allows you to apply a specified action to each element in the HashSet. This method is useful for iterating over all elements in the set and performing operations such as printing, modifying, or any custom action.

forEach Method Syntax

The syntax for the forEach method is as follows:

public void forEach(Consumer<? super E> action)
  • The method takes a single parameter action of type Consumer<? super E>, which specifies the action to be performed for each element.
  • The method does not return any value.

Examples

Printing Each Element of a HashSet

The forEach method can be used to print each element of the HashSet.

Example

import java.util.HashSet;

public class ForEachExample {
    public static void main(String[] args) {
        // Creating a HashSet of Strings
        HashSet<String> languages = new HashSet<>();

        // Adding elements to the HashSet
        languages.add("Java");
        languages.add("Python");
        languages.add("C");
        languages.add("JavaScript");

        // Printing each element using forEach
        System.out.println("Elements in the HashSet:");
        languages.forEach(System.out::println);
    }
}

Output:

Elements in the HashSet:
Java
C
Python
JavaScript

Modifying Each Element in a HashSet

While you can’t directly modify elements in an immutable collection like a HashSet, you can perform operations based on each element. For example, appending additional information to each element when printing.

Example

import java.util.HashSet;

public class ModifyEachElementExample {
    public static void main(String[] args) {
        // Creating a HashSet of Strings
        HashSet<String> languages = new HashSet<>();

        // Adding elements to the HashSet
        languages.add("Java");
        languages.add("Python");
        languages.add("C");
        languages.add("JavaScript");

        // Printing each element with a custom message using forEach
        System.out.println("Elements with custom messages:");
        languages.forEach(lang -> System.out.println("Programming Language: " + lang));
    }
}

Output:

Elements with custom messages:
Programming Language: Java
Programming Language: C
Programming Language: Python
Programming Language: JavaScript

Performing Complex Actions on Each Element

You can also perform more complex actions on each element using the forEach method, such as conditionally processing elements or accumulating results.

Example

import java.util.HashSet;

public class ComplexActionExample {
    public static void main(String[] args) {
        // Creating a HashSet of Strings
        HashSet<String> languages = new HashSet<>();

        // Adding elements to the HashSet
        languages.add("Java");
        languages.add("Python");
        languages.add("C");
        languages.add("JavaScript");

        // Performing complex actions: counting the number of languages with length greater than 3
        final int[] count = {0};
        languages.forEach(lang -> {
            if (lang.length() > 3) {
                count[0]++;
            }
        });

        // Printing the result
        System.out.println("Number of languages with length greater than 3: " + count[0]);
    }
}

Output:

Number of languages with length greater than 3: 3

Conclusion

The HashSet.forEach() method in Java provides a way to perform actions on each element in a HashSet. By understanding how to use this method, you can efficiently process all elements in the set, whether it’s printing, modifying, or performing any custom action. This method simplifies the iteration process and enhances code readability and maintainability.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top