Skip to content

Instantly share code, notes, and snippets.

@tsuyoshicho
Last active October 7, 2017 09:28
Show Gist options
  • Select an option

  • Save tsuyoshicho/12924dad2ed09aeb7ac859040a3c00f6 to your computer and use it in GitHub Desktop.

Select an option

Save tsuyoshicho/12924dad2ed09aeb7ac859040a3c00f6 to your computer and use it in GitHub Desktop.
JavaのEnumを別要素で検索する、の検討 ref: http://qiita.com/tsuyoshi_cho/items/698812641bcd45adbf41
/* 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment