Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Marvin Deutz
Marvin Deutz
8,349 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!

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.

cdlvr
cdlvr
14,448 Points

The efficiency difference for something like this is negligible in the grand scheme of things. Make the decision based on style preference and readability. Worry about the efficiency of different methods of searching/looping only if you're profiled a performance bottle neck related to that code.

Here's a slightly more succinct (IMO) Stream version:

public Gif findByName(String name) {
    return ALL_GIFS.stream()
            .filter(gif -> gif.getName().equals(name))
            .findFirst()
            .orElse(null);
}