Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream.of VS Arrays.stream to get an enum from a value

Tags:

java

enums

java-8

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();
    }
}
like image 416
Emilien Brigand Avatar asked Oct 29 '25 15:10

Emilien Brigand


1 Answers

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.

like image 199
Manikandan Avatar answered Nov 01 '25 05:11

Manikandan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!