com.softicar.platform.common.container.enums.IdToEnumMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of platform-common Show documentation
Show all versions of platform-common Show documentation
The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.
package com.softicar.platform.common.container.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
/**
* Efficient mapping of {@link Integer} to {@link Enum} constants.
*
* @author Oliver Richers
*/
public class IdToEnumMap> {
private final Map map;
public IdToEnumMap(Class enumClass, Function idMapper) {
this.map = new HashMap<>(enumClass.getEnumConstants().length);
for (E enumerator: enumClass.getEnumConstants()) {
map.put(idMapper.apply(enumerator), enumerator);
}
}
/**
* Returns the matching enumerator or null.
*
* If the given ID is null, this method return null.
*
* @param id
* the enumerator ID (may be null)
* @return the matching enumerator or null
*/
public E get(Integer id) {
if (id != null) {
return map.get(id);
} else {
return null;
}
}
public Optional getOptional(Integer id) {
return Optional.ofNullable(get(id));
}
}