Last active
October 7, 2017 09:28
-
-
Save tsuyoshicho/12924dad2ed09aeb7ac859040a3c00f6 to your computer and use it in GitHub Desktop.
JavaのEnumを別要素で検索する、の検討 ref: http://qiita.com/tsuyoshi_cho/items/698812641bcd45adbf41
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 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