Home > Software engineering >  How to use java stream to verify these conditions with returns
How to use java stream to verify these conditions with returns

Time:09-27

Let's say i have this enum class :

public enum Fruits{
    APPLE("apple"),
    ORANGE("orange"),
    BANANA("banana");

    private final String fruit;

    Fruit(String fruit)
    {
        this.fruit = fruit ;
    }

    public String toString(){
        return this.fruit;
    }

    public static Fruit fromString(String fruit) {
        for(Fruit f: Fruit.values()){
            if(f.toString().equals(fruit)){
                return f;
            }
        }
        return null;
    }
    }
}

I want to rewrite the fromString function to do the exact same thing but with a java stream(). My problem is that i'm not sure how to write it, i need it to either return f or a null but everytime i had returns it seems to not be working.

What i tried:

This one doesn't work because when i return s it says : unexpected value

Arrays.stream(Fruit.values())
            .forEach(f-> {
                if(s.toString().equals(fruit)){
                    return f;
                }
            });

Any idea how i can achieve this (if possible) ? Thanks a lot.

CodePudding user response:

Assuming, Semester.values() is an array of String.

String[] values = {"sem", "sem2"};
String semester = "sem";
Arrays.stream(values)
        .filter(v -> v.equals(semester))
        .findFirst()
        .orElse(null);

Use some IDE like STS or IntelliJ. IDEs show all functions implemented in these packages and their explanation. Or you can try some online tutorials.

  • Related