Java Spring Basics Modeling, Storing, and Presenting Data Create a Data Repository Component

Marvin Deutz
Marvin Deutz
8,344 Points

Stream or enhanced for loop

Wouldn't it be more efficient to use a Stream and filter for the findByName method? Was just wondering!

Liam Thornback
Liam Thornback
9,612 Points

I used a stream method like this:

public Gif findByName(String name) {
        //using java stream methods to find Gif
        Optional<Gif> match = ALL_GIFS.stream()
                .filter(item -> item.getName().equals(name))
                .findFirst();

        //if match is found return it, else return null
        return match.isPresent() ? match.get() : null;
    }

I think my code looks a little cleaner and is easier to follow (if you understand streams and a little functional programming).

For most, I would guess his method was probably easier to follow.

Also Intelij is complaining that my conditional can be rewritten in functional style, even though it already is in functional style....

Agreed and thanks! I was hoping to find this code in the q and a.