Среднее значение всех элементов массива java

Как найти среднее значение в массиве java

Чтобы найти среднее значение в массиве целых чисел в Java, можно использовать стримы. Преобразуем массив чисел в IntStream и найдем среднее значение:

import java.util.Arrays; int[] numbers = 1, 2, 3, 4, 5>; double average = Arrays.stream(numbers).average().getAsDouble(); System.out.println(average); // 3.0 

Источник

Найдите сумму и среднее значение в массиве Java

В этом кратком руководстве мы расскажем, как вычислить сумму и среднее значение в массиве, используя как стандартные циклы Java, так и Stream API.

2. Найдите сумму элементов массива​

2.1. Сумма с использованием цикла for

Чтобы найти сумму всех элементов в массиве, мы можем просто выполнить итерацию массива и добавить каждый элемент в переменную , накапливающую сумму . «

Это очень просто начинается с суммы 0 и добавляет каждый элемент в массив по мере продвижения:

 public static int findSumWithoutUsingStream(int[] array)    int sum = 0;   for (int value : array)    sum += value;   >   return sum;   > 

2.2. Сумма с Java Stream API

Мы можем использовать Stream API для достижения того же результата:

 public static int findSumUsingStream(int[] array)    return Arrays.stream(array).sum();   > 

Важно знать, что метод sum() поддерживает только потоки примитивного типа .

Если мы хотим использовать поток для упакованного целочисленного значения, мы должны сначала преобразовать поток в IntStream с помощью метода mapToInt .

После этого мы можем применить метод sum() к нашему только что преобразованному IntStream :

 public static int findSumUsingStream(Integer[] array)    return Arrays.stream(array)   .mapToInt(Integer::intValue)   .sum();   > 

Вы можете прочитать намного больше о Stream API здесь .

3. Найдите среднее значение в массиве Java​

3.1. В среднем без Stream API

Как только мы узнаем, как вычислить сумму элементов массива, найти среднее значение довольно легко — так как Среднее = сумма элементов / количество элементов :

 public static double findAverageWithoutUsingStream(int[] array)    int sum = findSumWithoutUsingStream(array);   return (double) sum / array.length;   > 
  1. Деление int на другое int возвращает результат int . Чтобы получить точное среднее значение, мы сначала приводим сумму к удвоению .
  2. Массив Java имеет поле длины , в котором хранится количество элементов в массиве.

3.2. Среднее с использованием Java Stream API

 public static double findAverageUsingStream(int[] array)    return Arrays.stream(array).average().orElse(Double.NaN);   > 

IntStream.average() возвращает OptionalDouble , который может не содержать значения и требует специальной обработки.

Подробнее о Optionals читайте в этой статье, а о классеOptionalDouble — в документации по Java 8 .

4. Вывод​

В этой статье мы рассмотрели, как найти сумму/среднее значение элементов массива int .

Источник

Нахождение суммы и среднего значения в массиве Java

В этом кратком руководстве мы рассмотрим, как вычислить сумму и среднее значение в массиве Java, используя стандартные циклы.

Чтобы найти сумму всех элементов в массиве, мы можем просто перебрать массив и добавить каждый элемент к суммирующей переменной.

public static int findSumWithoutUsingStream(int[] array) < int sum = 0; for (int value : array) < sum += value; >return sum; >

или вычисляем сумму используя индексы:

int array[] = ; int sum = 0; for (int i = 0; i < array.length; ++i) sum += array[i];

Можно использовать Stream API для достижения того же результата:

public static int findSumUsingStream(int[] array)

Важно знать, что метод sum() поддерживает примитивные типы.

Если мы хотим использовать целочисленные значения, сначала нужно преобразовать поток в IntStream, используя mapToInt метод. После этого применить метод sum() к нашему недавно преобразованному IntStream:

public static int findSumUsingStream(Integer[] array)

Найти среднее значение элементов массива Java довольно легко. Напомним, что среднее = сумма чисел/количество чисел.

public static double findAverageWithoutUsingStream(int[] array) < int sum = findSumWithoutUsingStream(array); return (double) sum / array.length; >

Примечание: деление int на int возвращает результат int. Джава массив имеет поле length, в котором хранится количество элементов.

Если подсчитывать через Java Stream API, то код умещается в одну строчку:

public static double findAverageUsingStream(int[] array)

IntStream.average () возвращает OptionalDouble, который может не содержать значения и требует специальной обработки.

Чтобы узнать больше об OptionalDouble class, читайте документацию по Java 8.

Исходный код можно скачать тут.

Средняя оценка 2.6 / 5. Количество голосов: 5

Спасибо, помогите другим - напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Calculating average of an array list?

I'm trying to use the below code to calculate the average of a set of values that a user enters and display it in a jTextArea but it does not work properly. Say, a user enters 7, 4, and 5, the program displays 1 as the average when it should display 5.3

 ArrayList marks = new ArrayList(); Collections.addAll(marks, (Integer.parseInt(markInput.getText()))); private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) < analyzeTextArea.setText("Class average:" + calculateAverage(marks)); >private int calculateAverage(List marks) < int sum = 0; for (int i=0; i< marks.size(); i++) < sum += i; >return sum / marks.size(); > 

11 Answers 11

OptionalDouble average = marks .stream() .mapToDouble(a -> a) .average(); 

Thus your average value is average.getAsDouble()

return average.isPresent() ? average.getAsDouble() : 0; 

average.isPresent() ? average.getAsDouble() : defaultValue can be simplified further to optional.orElse( defaultValue )

Why use a clumsy for loop with an index when you have the enhanced for loop?

private double calculateAverage(List marks) < Integer sum = 0; if(!marks.isEmpty()) < for (Integer mark : marks) < sum += mark; >return sum.doubleValue() / marks.size(); > return sum; > 

Update: As several others have already pointed out, this becomes much simpler using Streams with Java 8 and up:

private double calculateAverage(List marks) < return marks.stream() .mapToDouble(d ->d) .average() .orElse(0.0) > 

Just a quick note, one reason to use the clumsy loop is that it is a lot faster than the so-called civilized loop. For ArrayLists, the for(int i = 0 . ) loop is about 2x faster than using the iterator or the for (:) approach, so even though it's prettier, it's a lot slower! One tip to make it go even faster is to cache the length as follows: for (int i = 0, len = list.size(); i

they're actually about as fast in properly done test. interestingly enough the "enhanced for loop" and the traditional for loop ends up being executed just as fast as a while(i-->0) one, despite having an extra evaluation/call per loop. this just running on se1.7, with the arraylist filled with objects having a random int as member variable and calculating that to a sum, to make the vm do actual work. enhanced loop is about as fast as iterating yourself with iterator. if you're using arraylist, no point in using the enhanced since index based gets are faster and less gc causing.

A bit off-topic here but I was using this method in Android but Android Studio told me that the for loop required an Object type like for(Object mark: marks) (I really don't know why) obviously comes out another error inside the loop "Operator '+' cannot be applied to 'java.lang.Double', 'java.lang.Object'" so I had to cast mark to Double: sum += (Double)mark;

From Java8 onward you can get the average of the values from a List as follows:

 List intList = Arrays.asList(1,2,2,3,1,5); Double average = intList.stream().mapToInt(val -> val).average().orElse(0.0); 

This has the advantage of having no moving parts. It can be easily adapted to work with a List of other types of object by changing the map method call.

 List dblList = Arrays.asList(1.1,2.1,2.2,3.1,1.5,5.3); Double average = dblList.stream().mapToDouble(val -> val).average().orElse(0.0); 

NB. mapToDouble is required because it returns a DoubleStream which has an average method, while using map does not.

@Test public void bigDecimalListAveragedCorrectly() < ListbdList = Arrays.asList(valueOf(1.1),valueOf(2.1),valueOf(2.2),valueOf(3.1),valueOf(1.5),valueOf(5.3)); Double average = bdList.stream().mapToDouble(BigDecimal::doubleValue).average().orElse(0.0); assertEquals(2.55, average, 0.000001); > 

using orElse(0.0) removes problems with the Optional object returned from the average being 'not present'.

I do not think the third method is working (using mapToDouble(BigDecimal::doubleValue).average() ). You should use BigDecimal::valueOf instead.

And actually even that, you are still wrong, since average is only working for primitive types.

Use a double for the sum, otherwise you are doing an integer division and you won't get any decimals:

private double calculateAverage(List marks) < if (marks == null || marks.isEmpty()) < return 0; >double sum = 0; for (Integer mark : marks) < sum += mark; >return sum / marks.size(); > 

or using the Java 8 stream API:

 return marks.stream().mapToInt(i -> i).average().orElse(0); 

It would be cleaner to caste to a double just before you return so you don't get any floating point errors creep in when marks is a very large list.

You're adding the index; you should be adding the actual item in the ArrayList :

Also, to ensure the return value isn't truncated, force one operand to double and change your method signature to double :

return (double)sum / marks.size(); 

Using Guava, it gets syntactically simplified:

List.stream().mapToDouble(a->a).average() 

Try to use code formatting and provide some context to your answer. See the other answers as examples.

When the number is not big, everything seems just right. But if it isn't, great caution is required to achieve correctness.

Take double as an example:

If it is not big, as others mentioned you can just try this simply:

doubles.stream().mapToDouble(d -> d).average().orElse(0.0); 

However, if it's out of your control and quite big, you have to turn to BigDecimal as follows (methods in the old answers using BigDecimal actually are wrong).

doubles.stream().map(BigDecimal::valueOf).reduce(BigDecimal.ZERO, BigDecimal::add) .divide(BigDecimal.valueOf(doubles.size())).doubleValue(); 

Enclose the tests I carried out to demonstrate my point:

 @Test public void testAvgDouble() < assertEquals(5.0, getAvgBasic(Stream.of(2.0, 4.0, 6.0, 8.0)), 1E-5); ListdoubleList = new ArrayList<>(Arrays.asList(Math.pow(10, 308), Math.pow(10, 308), Math.pow(10, 308), Math.pow(10, 308))); // Double.MAX_VALUE = 1.7976931348623157e+308 BigDecimal doubleSum = BigDecimal.ZERO; for (Double d : doubleList) < doubleSum = doubleSum.add(new BigDecimal(d.toString())); >out.println(doubleSum.divide(valueOf(doubleList.size())).doubleValue()); out.println(getAvgUsingRealBigDecimal(doubleList.stream())); out.println(getAvgBasic(doubleList.stream())); out.println(getAvgUsingFakeBigDecimal(doubleList.stream())); > private double getAvgBasic(Stream doubleStream) < return doubleStream.mapToDouble(d ->d).average().orElse(0.0); > private double getAvgUsingFakeBigDecimal(Stream doubleStream) < return doubleStream.map(BigDecimal::valueOf) .collect(Collectors.averagingDouble(BigDecimal::doubleValue)); >private double getAvgUsingRealBigDecimal(Stream doubleStream) < Listdoubles = doubleStream.collect(Collectors.toList()); return doubles.stream().map(BigDecimal::valueOf).reduce(BigDecimal.ZERO, BigDecimal::add) .divide(valueOf(doubles.size()), BigDecimal.ROUND_DOWN).doubleValue(); > 

As for Integer or Long , correspondingly you can use BigInteger similarly.

Источник

Как найти среднее арифметическое в массиве java

Найти среднее арифметическое всех чисел в массиве можно разными способами. Можно перебрать весь массив при помощи цикла, сложить все элементы массива и поделить на размер массива. Можно также использовать стримы, этот вариант будет более лаконичный. Рассмотрим пример со стримами:

import java.util.Arrays; int[] coll = 1, 2, 3, 4, 5, 6>; var average = Arrays.stream(coll) .average() .getAsDouble(); System.out.println(average); // => 3.5 

Источник

Читайте также:  Python import same file
Оцените статью