Thursday, December 21, 2017

Java 8: Calculate average, sum, maximum, minimum and count of elements of a list

The easiest way probably is to get the summary statistics of the list through stream first. Get all the values, then, from the summary statistics. Below is an example for a integer list. The same logic applies to all other type of numbers.

List<Integer> intList = Arrays.asList(123, 886, 43, 25, 33, 89);

IntSummaryStatistics intStat = intList.stream()
            .mapToInt ( i -> i)
            .summaryStatistics();

double average = intStat.getAverage();
long sum = intStat.getSum();
long count = intStat.getCount();
int max = intStat.getMax();
int min = intStat.getMin();

Of course, if you just want to get the sum or find the maximum, you can do it like below.

int sum = intList.stream()
           .mapToInt(i -> i)
           .sum();

int max = intList.stream()
           .mapToInt(i -> i)
           .max()
           .orElse(0);

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment