How does this filter apply in Java 8?

First of all, I apologize for the title of the problem. I can't think of a better way to express it. If I should solve it, please let me know

Basically, I am a java programmer. I use imperative programming too much to discover (and play) the new functions of Java 8

The method I wrote is very simple, and I work normally. I just want to know if there is a more "functional" solution

Basically, I receive a list of users and need to return the percentage of users with status = invalid

So that's what I've done 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();
}

If possible, I want to use it as a liner. I know it may be over thinking, but I want to know the limitations and possibilities of the language I use

Thank you for your time

Solution

The following should be valid

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

It maps the status to 0 or 100 and averages it This means that for each invalid user, you have a 100, and for each other user you have 0, the average is the exact result of your request

100 times your 100 If you want to use a percentage to represent a percentage, replace it with 1

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>