Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java 8, how do I apply this filter?

First of all I apologize for the title of the question, I couldn't think of a better way to phrase it, please let me know if I should fix it.

Basically I'm a Java programmer that is way too used with imperative programming, discovering (and playing with) the new features from Java 8.

The method I am writing is quite simple, and I have it working fine, I'm just wondering if there's a more "functional" way of solving this.

Basically I receive a list of User, and need to return the percentage of those users that have Status = INVALID.

So here's what I did so far:

public static double getFailedPercentage(List<User> users){
    Long failedCount = users.stream().filter(user -> User.Status.INVALID.equals(user.getStatus())).collect(counting());
    return (failedCount * 100) / users.size();
}

I would like to keep this as a one liner if possible, I know this might be overthinking things, but I like to know the limits and the possibilities of the language I use.

Thanks in advance for your time.

like image 911
Rodrigo Sasaki Avatar asked Nov 22 '25 13:11

Rodrigo Sasaki


1 Answers

The following should work

return users.stream()
            .mapToInt(user -> User.Status.INVALID.equals(user.getStatus()) ? 100 : 0)
            .average()
            .getAsDouble();

It maps the Status to either 0 or 100 and then takes the average. Which means for every INVALID user you have a 100, for every other you have a 0, the average of that is the exact result as you requested.

The 100 is the same hundred you multiplied by. If you want a decimal representation of the percentage, replace it with a 1.

https://docs.oracle.com/javase/tutorial/collections/streams/

like image 76
luk2302 Avatar answered Nov 24 '25 01:11

luk2302