Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
Pedro Pereira Avatar asked Aug 06 '26 19:08

Pedro Pereira


1 Answers

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.

like image 169
Mario Ishac Avatar answered Aug 09 '26 10:08

Mario Ishac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!