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

Given two EnumSet collections, we have to remove Elements of an EnumSet collection that does not exist in another EnumSet collection.
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 remove elements of an EnumSet Collection that does not exist in the specified EnumSet collection using the retainAll() method.

Program/Source Code:

The source code to remove Elements of an EnumSet collection that does not exist in another EnumSet collection is given below. The given program is compiled and executed successfully.

// Java program to remove Elements of an EnumSet collection 
// that does not exist in another 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.GREEN);
    enumSet2.add(COLORS.BLUE);

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

    enumSet1.retainAll(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: [GREEN, BLUE]

Elements of enumSet1: [GREEN, BLUE]
Elements of enumSet2: [GREEN, BLUE]

Explanation:

Here, we created two EnumSet collections and add elements to them. Then we used retainAll() method to remove elements of enumSet1 that are not 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.