fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.function.*;
  7.  
  8. interface Searchable {
  9. public static <T extends Enum,N extends Comparable> Optional<T> getByCode(Supplier<T[]> v,Function<T,N> s,N code)
  10. {
  11. return Arrays.stream(v.get())
  12. .filter(data -> s.apply(data).equals(code))
  13. .findFirst();
  14. }
  15. }
  16.  
  17. enum TestEnum implements Searchable {
  18. A(1),B(2),C(3);
  19. private final Integer id;
  20. private TestEnum (int id) { this.id = id;}
  21.  
  22. public Integer getId() { return id; }
  23.  
  24. public static Optional<TestEnum> getById(Integer id){
  25. return Searchable.getByCode(TestEnum::values,TestEnum::getId,id);
  26. }
  27. }
  28.  
  29. /* Name of the class has to be "Main" only if the class is public. */
  30. class Ideone
  31. {
  32. public static void main (String[] args) throws java.lang.Exception
  33. {
  34. TestEnum.getById(2).ifPresent(System.out::println);
  35. }
  36. }
Success #stdin #stdout 0.12s 4386816KB
stdin
Standard input is empty
stdout
B