Constantine Gladky
Constantine Gladky

Reputation: 1263

How to return enum value by 2 parameters in java

I have such enum class in java

    public enum MockTypes
    {
        // Atlantis mocks
        ATLANTIS_VERIFY("ATLANTIS", "verify"),
        ATLANTIS_CREATE_RECORD("ATLANTIS", "createRecord"),

    ...

        private String m_adaptor;

        private String m_step;

private MockTypes( String adaptor, String step)
    {
        m_adaptor = adaptor;
        m_step = step;
    }

             public String getAdaptor()
        {
            return m_adaptor;
        }

        public String getStep()
        {
            return m_step;
        }

I have to implement method that returns enum value by adaptor and step parameter.

public MockTypes getMockTypeByName(String adaptor, String step)

but I have no idea how. Could someone help me?

Upvotes: 8

Views: 14213

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198033

If you want a "constant-time" solution that doesn't involve looking up values, your best option is to initialize a constant Map in a static block in the MockType class.

If you're up for using Guava, it'll actually be relatively pleasant:

public enum MockType {
  ...

  private static final ImmutableTable<String, String, MockType> LOOKUP_TABLE;

  static {
    ImmutableTable.Builder<String, String, MockType> builder =
      ImmutableTable.builder();
    for (MockType mockType : MockType.values()) {
      builder.put(mockType.getAdaptor(), mockType.getStep(), mockType);
    }
    LOOKUP_TABLE = builder.build();
  }

  public static MockType getMockType(String adaptor, String step) {
    return LOOKUP_TABLE.get(adaptor, step);
  }
}

(Disclosure: I contribute to Guava.)

The alternative is going to be relatively similar -- construct a Map<String, Map<String, LookupType>> in a static block, and do lookups from there -- though it's going to require somewhat more work.

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117589

public MockTypes getMockTypeByName(String adaptor, String step)
{
    for(MockTypes m : MockTypes.values())
    {
        if(m.getAdaptor().equals(adaptor) && 
           m.getStep().equals(step)) return m;
    }
    return null;
}

Upvotes: 14

rid
rid

Reputation: 63442

You can use enum's values() method to obtain a list of all the defined values. You can then loop through this list and find the values you're interested in that match the ones sent as parameters to the method.

Upvotes: 1

Related Questions