With Java 8 I found a common way to get an enum from a value, it's using an Arrays.stream with a filter on all the enum values, but recently, I came across another way to do it, with Stream.of, what is the better way between each other and why? Is there another better way to do it?
Example:
public enum Foo {
BAR_1("Bar 1"),
BAR_2("Bar 2");
private String friendlyValue;
Foo(String friendlyValue){
this.friendlyValue = friendlyValue;
}
public String getFriendlyValue() {
return friendlyValue;
}
public static Foo fromFriendlyValue1(String friendlyValue){
return Stream.of(Foo.values()).filter(r -> r.getFriendlyValue().equals(friendlyValue)).findFirst().get();
}
public static Foo fromFriendlyValue2(String friendlyValue) {
return Arrays.stream(Foo.values()).filter(r -> r.getFriendlyValue().equals(friendlyValue)).findFirst().get();
}
}
Stream.of is actually using Arrays.stream.
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
So you can directly use Arrays.stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With