Java-stream (replacement for-loop)

Viewed 121

I'm new to Java and learning / trying to understand the system with the Streams.

In an example I have following code:

private Comment findComment(String author)
{                 
   for(Comments comment : comments) {
        if(comment.getAuthor().equals(author)) {
            return comment;
        }
    }
    return null;
}

For training purpose I started to rewrite some old method's (most of them with for-loops) with streams to get more practice. But this little method kept me going for more than three ours with javadocs (+Google) and I still do not know what's wrong - it won't even compile :/

Here my "new" code which should replace the above:

private Comment findComment(String author)
{
    return comments.stream()
              .filter(s -> author.equals(s.getAuthor()))
              .findFirst();
}

The ArrayList comments can (at the time) store only one comment from an author. If an author writes a new comment the old one gets deleted. That would mean that the .findFirst(); is not really necessary.

In my opinion it should be possible to narrow the ArrayList down until there is only one object left and give it back to the return statement... Am I right or do I forget something?

Edit (01.12.2020, 10:13): I had to edit the first code snippet. The return statement was wrong (typo...)

1 Answers

findFirst returns an Optional. In order to convert that Optional to a Comment object, and handle the case where no Comment is found while you're at it, you could use orElse:

private Comment findComment(String author)
{
    return comments.stream()
              .filter(s -> author.equals(s.getAuthor()))
              .findFirst()
              .orElse(null); // Here
}
Related