3

I have a method that calculates the number of posts made by a user like this:

public long nrPostUser(String user)
    {
        return this.posts.stream().filter(a-> a.getName().equals(user) ).count();
    }

as a training exercise i wanted to do the same thing but using a double colon operator instead of the lambda expression, I managed to do it by hardcoding the user parameter like so:

public long nrPostUser2(String user)
    {
        return  this.posts.stream().filter(FBPost::isUser).count();
    }

public boolean isUser()
    {
        return this.name.equals("1");
    }

My problem here is that I can't seem to make so that I can make use of a non-hardcoded version of this, from what I've seen it should be something like this:

public long nrPostUser3(String user)
    {
        Function<String,Boolean> func = FBPost::isUser2;
        return (int) this.posts.stream().filter(FBPost::isUser).count();
    }

public boolean isUser2(String user)
    {
        return this.name.equals(user);
    }

but that doesn't work.

1
  • 1
    To clarify, by hardcoding you mean using the function reference directly, as opposed to assigning it to a variable first and using the variable instead? I think it's totally fine and the feature was most likely designed to be used in this way. Commented Jul 3, 2020 at 14:12

1 Answer 1

3

You can do this:

public long nrPostUser(String user) {
    return posts.stream()
            .map(FBPost::getName)
            .filter(user::equals)
            .count();
}

Because we're using count and ultimately don't care about the resulting stream before we call count, we can use map to get all the post's users before filtering on their equality with user.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.