Java program to add Elements of an EnumSet collection to the other EnumSet collection

Given two EnumSet collections, we have to add elements of one EnumSet to another.
Submitted by Nidhi, on May 31, 2022

Problem Solution:

In this program, we will create an Enum for COLORS constants. Then we will add elements to created EnumSet collections. After that, we add elements of an EnumSet Collection to another EnumSet collection using the addAll() method.

Program/Source Code:

The source code to add Elements of an EnumSet collection to the other EnumSet collection is given below. The given program is compiled and executed successfully.

// Java program to add Elements of an EnumSet collection 
// to the other EnumSet collection

import java.util.*;

//Enum for color constants
enum COLORS {
  RED,
  GREEN,
  BLUE,
  BLACK,
  WHITE
};

public class Main {
  public static void main(String[] args) {
    EnumSet < COLORS > enumSet1 = EnumSet.noneOf(COLORS.class);
    EnumSet < COLORS > enumSet2 = EnumSet.noneOf(COLORS.class);

    enumSet1.add(COLORS.RED);
    enumSet1.add(COLORS.GREEN);
    enumSet1.add(COLORS.BLUE);

    enumSet2.add(COLORS.BLACK);
    enumSet2.add(COLORS.WHITE);

    System.out.println("Elements of enumSet1: " + enumSet1);
    System.out.println("Elements of enumSet2: " + enumSet2);

    enumSet1.addAll(enumSet2);

    System.out.println("\nElements of enumSet1: " + enumSet1);
    System.out.println("Elements of enumSet2: " + enumSet2);
  }
}

Output:

Elements of enumSet1: [RED, GREEN, BLUE]
Elements of enumSet2: [BLACK, WHITE]

Elements of enumSet1: [RED, GREEN, BLUE, BLACK, WHITE]
Elements of enumSet2: [BLACK, WHITE]

Explanation:

Here we created two EnumSet collections and add elements to them. Then we used addAll() method to add elements of enumSet2 into enumSet1. After that, we printed the updated collections.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.