user1097772 user1097772 - 1 year ago 70
Java Question

Proper way testing that String belongs to subset of constants (Java)


  • Represent subset of Strings created from Strings defined in abstract class

  • test if string on input belongs to given subset

Initial solution:

Let's have list of possible events.

* List of events.
public abstract class EventKeys {

public static final String KEY_EVENT_1 = "EVENT_1";
public static final String KEY_EVENT_2 = "EVENT_2";
public static final String KEY_EVENT_3 = "EVENT_3";
public static final String KEY_EVENT_4 = "EVENT_4";
public static final String KEY_EVENT_5 = "EVENT_5";
public static final String KEY_EVENT_6 = "EVENT_6";
public static final String KEY_EVENT_7 = "EVENT_7";
//etc ..

I want make subset of these events for example events 1,3,5 and only for these events allow some action. The goal is make method boolean isEventAllowed(String eventKey) which will say if event belongs to subset of allowed events.

The really naive way to do this is:

* Allow only events 1,3,5
private isEventAllowed(String eventKey) {

if(eventKey.equals(EventKeys1.KEY_EVENT_1)) {
return true;
} else if(eventKey.equals(EventKeys1.KEY_EVENT_3)) {
return true;
} else if(eventKey.equals(EventKeys1.KEY_EVENT_3)) {
return true;
} else {
return false;

The I feel this approach is not very convinient. I need better way to represent the subset of strings and provide action does input string belongs to defined subset?

Other possible solutions:

As other options i was thinking about other two options, but I'm still not sure if its good way to do it.
1)enum - create enum of strings

  • Put in enum: EventKeys1.KEY_EVENT_1, EventKeys1.KEY_EVENT_2, EventKeys1.KEY_EVENT_3

  • Test does String keyEvent belons to defined enum?

2) list

  • create list
    List<String> subset
    and put there
    EventKeys1.KEY_EVENT_1, EventKeys1.KEY_EVENT_2, EventKeys1.KEY_EVENT_3

  • test if String keyEvent belongs to list subset


  • class EventKeys is given, can't be changed, main set of options

  • I need somehow represent subset

  • I need advice for better implementation of method isAllowedEvent(String keyEvent) which returns true if input string
    belongs to defined subset

Answer Source

How about something like this?

    private boolean isEventAllowed(String eventKey) {
      return Arrays.asList(KEY_EVENT_1, KEY_EVENT_3, KEY_EVENT_5).contains(eventKey);

Readability could be improved following John Fergus' comment by using something like this:

    private static List<String> SUBSET = Arrays.asList(KEY_EVENT_1, KEY_EVENT_3, KEY_EVENT_5);

    private boolean isEventAllowed(String eventKey) {
      return SUBSET.contains(eventKey);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download