- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find average of a list in Java
To find average of a list in Java, the code is as follows -
Example
import java.util.*; public class Demo { public static void main(String []args){ List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500); IntSummaryStatistics summaryStats = list.stream() .mapToInt((a) -> a) .summaryStatistics(); System.out.println("Average of a List = "+summaryStats.getAverage()); } }
Output
Average of a List = 156.66666666666666
Let us now see another example -
Example
import java.util.*; public class Demo { public static void main(String []args){ List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500); int sum = 0; for (int i : list) { sum+=i; } if(list.isEmpty()){ System.out.println("Empty list!"); } else { System.out.println("Average = " + sum/(float)list.size()); } } }
Output
Average = 156.66667
Advertisements