Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use java stream to verify these conditions with returns

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading