I tried to collect and implement information on "Search Java Enum by another element" which is sometimes talked about. I think it's a decent one, but there are many problems that can't be solved.
test.java
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.function.*;
interface Searchable {
public static <T extends Enum,N extends Comparable> Optional<T> getByCode(Supplier<T[]> v,Function<T,N> s,N code)
{
return Arrays.stream(v.get())
.filter(data -> s.apply(data).equals(code))
.findFirst();
}
}
enum TestEnum implements Searchable {
A(1),B(2),C(3);
private final Integer id;
private TestEnum (int id) { this.id = id;}
public Integer getId() { return id; }
public static Optional<TestEnum> getById(Integer id){
return Searchable.getByCode(TestEnum::values,TestEnum::getId,id);
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
TestEnum.getById(2).ifPresent(System.out::println);
}
}
The key element is
However
There are many places to worry about To be honest, it would be more convenient to add an identification and search API by adding enum class accessors and member accessors to the Lombok library.
It seems good to put what you have in the comments at the core of use.