Search code examples
javalambdamethod-reference

Problem using double colon expression in Java


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.


Solution

  • 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.