Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch a subset of an enumeration

Tags:

java

Most of the times an enumeration containing all elements is shown in a drop down in the user interface. We have a need to show only 2 out of 5 fields in the user interface. What would be an easier way to fetch this data, by somehow leveraging the same functions available for an enumeration.

enum Color {RED, GREEN, BLACK, BLUE, YELLOW};

We have a requirement to show only {RED, BLUE} in a certain user interface?

like image 277
user339108 Avatar asked Sep 24 '10 10:09

user339108


People also ask

Can you subclass an enum?

We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.

Can you inherit from an enum?

As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.

Can enumerations have methods?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

What is enumerated set?

An enumerated set is a finite or countable set or multiset S together with a canonical enumeration of its elements; conceptually, this is very similar to an immutable list.


3 Answers

Sounds like a job for EnumSet:

EnumSet<Color> set = EnumSet.of(Color.RED, Color.BLUE);
like image 109
Michael Borgwardt Avatar answered Oct 02 '22 22:10

Michael Borgwardt


EnumSet.of(Color.RED, Color.BLUE)

see java.util.EnumSet

like image 22
Bozho Avatar answered Sep 29 '22 22:09

Bozho


If enum contains some custom methods (e.g., to display Red instesd of RED)

public enum Color {
    RED("Red"), GREEN("Green"), BLACK("Black"), BLUE("Blue"), YELLOW("Yellow");

    private final String display;

    private Color(String display) {
        this.display = display;
    }

    @Override
    public String toString() {
        return display;
    }

    public static EnumSet<Color> getSubSetOfValues() {
        return EnumSet.of(RED, BLUE); // return Red and Green
        //return EnumSet.range(GREEN, BLUE); // return Green, Black and Blue
    }
}

Color.values(); // all elements.

Color.getSubSetOfValues(); // subset

like image 1
Mokarrom Hossain Avatar answered Oct 03 '22 22:10

Mokarrom Hossain