I have the enum
as:
public enum EnumStatus {
PASSED(40L, \"Has Passed\"),
AVERAGE(60L, \"Has Average Marks\"),
GOOD(80L, \"Has Good
public static EnumStatus getById(long id)
{
for (EnumStatus e : EnumStatus.values())
{
if (id == e.getId()) return e;
}
throw new IllegalArgumentException("oh no");
}
This pattern can help you:
public interface Identifiable<T extends Number> {
@Nonnull
T getId();
}
public final class GettableById<K extends Number, V extends Enum<V> & Identifiable<K>> {
@Nonnull
private final Map<K, V> idToValue;
public GettableById(@Nonnull V[] values) {
this.idToValue = Arrays.stream(values)
.collect(Collectors.toUnmodifiableMap(Identifiable::getId, v -> v));
}
@Nonnull
public V getById(@Nonnull K id) {
var value = idToValue.get(id);
if (value != null) {
return value;
}
throw new NullPointerException("Cannot get value by id: %s".formatted(id));
}
}
public enum DataType implements Identifiable<Short> {
ANNUAL((short) 1), QUARTERLY((short) 2);
private static final GettableById<Short, DataType> companion = new GettableById<>(values());
@Nonnull
private final Short id;
public static DataType getById(Short id) {
return companion.getById(id);
}
DataType(@Nonnull Short id) {
this.id = id;
}
@Nonnull
@Override
public Short getId() {
return id;
}
}
Create a static method in your enum
which searches in values
(implicit method/member, don't know exactly which is it) and returns the corresponding value. For cases in which the method can not find a matching value, you should create a special entry, e.g. UNKNOWN
, which you can return. This way, you do not have to return null
, which is always a bad idea.
public static EnumStatus getById(Long id) {
for(EnumStatus e : values()) {
if(e.id.equals(id)) return e;
}
return UNKNOWN;
}
Btw - your code seems to be wrong. The bracket after GOOD
seems to not belong there.
You make this work as follows:
public static String fromId(long id) {
for (EnumStatus es : EnumStatus.values()) {
if (es.id.equals(id)) {
return es.getName();
}
}
throw new IllegalArgumentException();
}
Iterate over all the values and compare Id
for (EnumStatus enumStatus : EnumStatus.values()) {
if (..) {..}
}