0

I have an Enum class with a huge amount of values (translation keys to use with the database), but in my case I would only need to iterate over values of it which start for example with characters "c_foo_"

What would be the most cost efficient way to do this?

I'm using Java 14.

Naman
  • 23,555
  • 22
  • 173
  • 290
Steve Waters
  • 2,637
  • 7
  • 37
  • 80
  • Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Alireza Nov 04 '20 at 09:03
  • You can use a `Trie` or a `PatriciaTrie` if you are only interested in values starting with a certain prefix. Java natively does not provide an implementation, however, Apache Commons does. – Glains Nov 04 '20 at 09:11

2 Answers2

1

You can make use of Streams from the enum's values to filter out those you're not interested in.

Arrays.stream(YourEnum.values())
    .filter(e -> e.name().startsWith("c_foo_"))
    .forEach(...);
QBrute
  • 3,470
  • 6
  • 30
  • 36
0

Another possible way could be, presupposed your enum values have a defined order:

public enum MyEnum {
    BAR, BAZ, DOO, FOO, GEE, MOO
}

you could use EnumSet.range :

EnumSet<MyEnum> set = EnumSet.range(MyEnum.BAZ, MyEnum.GEE);

to get all the elements from BAZ to GEE following the order defined in the enum

[BAZ, DOO, FOO, GEE]

Notice that both first and last elements are inclusiv.

Eritrean
  • 9,903
  • 1
  • 15
  • 20
  • 1
    A valid solution, but general guidelines (for example Effective Java, Item 35: _Instance fields instead of ordinals_ [Bloch]) do not recommend to rely on the `ordinal()` method of an enum. Relying on alphanumeric ordering would imply the same. – Glains Nov 04 '20 at 10:15