Consider searching Java Enum by another element

Text

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.

Prototype with ideone

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

  1. Provide a search (acquisition) means other than valueOf
  2. Allow arbitrary addition ex enum Allow male (0, "M"), female (1, "F") to getByCode, getBySymbol for gender
  3. Somehow make it identifiable to have it (interface)

However

  1. There is no particular merit of inheriting (static can not be inherited)
  2. I can't have class information in generics (class generics can't be used statically, but it can't be helped as an eraser) Regarding 3.2, T.values () cannot be used when you bring it in the method generics, so you need the same arguments every time.
  3. Become Optional (this is unavoidable because it may not be available)
  4. (Although it is not necessary, there is no basic type member (because it cannot be equalized))

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.

Postscript

It seems good to put what you have in the comments at the core of use.

Based on the idea, a helpful link

Recommended Posts

Consider searching Java Enum by another element
[Java] enum
[Java] Dynamic method call by reflection of enum (enum)
Java Enum utilization example
Enum reverse map Java
[Java] About enum type