×

Java Programs

Java Practice

Java program to remove Elements of an EnumSet collection that exist in another EnumSet collection

Given two EnumSet collections, we have to remove Elements of an EnumSet collection that exist in another EnumSet collection.
Submitted by Nidhi, on May 31, 2022

Problem statement

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

Source Code

The source code to remove Elements of an EnumSet collection that exist in another 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 removeAll() method to remove elements of enumSet1 that are exist in enumSets. After that, we printed the updated collections.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





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