Найти наибольший элемент массива java

Как найти максимальное значение в массиве java

Чтобы найти максимальное значение в массиве необходимо пройтись по всем элементам в цикле, каждый раз сравнивая промежуточный максимум с очередным элементом массива. Если элемент в массиве больше промежуточного максимума, то нужно сохранить новое значение, как новый промежуточный максимум.

int[] arr = 10, 7, 1, 4, 7, 4, 11>; // Предположим, что нулевой элемент максимальный int max = arr[0]; // В цикле начинаем с первой ячейки for (int i = 1; i  arr.length; i++)  if (arr[i] > max)  max = arr[i]; > > System.out.println(max); // => 11 

Источник

Find Max and Min in an Array in Java

Learn to find the smallest and the largest item in an array in Java. We will discuss different approaches from simple iterations to the Stream APIs.

In the given examples, we are taking an array of int values. We can apply all the given solutions to an array of objects or custom classes as well. In the case of custom objects, we only need to override the equals() method and provide the correct logic to compare two instances.

int[] items = < 10, 0, 30, 2, 7, 5, 90, 76, 100, 45, 55 >; // Min = 0, Max = 100

1. Find Max/Min using Stream API

Java streams provide a lot of useful classes and methods for performing aggregate operations. Let’s discuss a few of them.

The Stream interface provides two methods max() and min() that return the largest and the smallest item from the underlying stream.

Both methods can take a custom Comparator instance if we want a custom comparison logic between the items.

For primitives, we have IntStream , LongStream and DoubleStream to support sequential and parallel aggregate operations on the stream items. We can use the java.util.Arrays.stream() method to convert the array to Stream and then perform any kind of operation on it.

int max = Arrays.stream(items) .max() .getAsInt(); // 100 int min = Arrays.stream(items) .min() .getAsInt(); // 0

In the above example, we find the array’s max and min items in two separate steps. We are creating the stream two times and operating on it two times. This is useful when we only have to find either the maximum item or the minimum item.

If we have to find the max and min item both then getting the max and min item from the array in a single iteration makes complete sense. We can do it using the IntSummaryStatistics instance. A similar instance is available for LongStream and DoubleStream as well.

IntSummaryStatistics stats = Arrays.stream(items).summaryStatistics(); stats.getMax(); //100 stats.getMin(); //0

2. Collections.min() and Collections.max()

The Collections class provides the aggregate operations for items in a collection such as List. We can convert an array into a List and use these APIs to find the max and min items.

In the given example, we are converting the int[] to Integer[]. If you have an Object[] already then you can directly pass the array to Arrays.asList() API.

Integer min = Collections.min(Arrays.asList(ArrayUtils.toObject(items))); Integer max = Collections.max(Arrays.asList(ArrayUtils.toObject(items)));

Sorting the array is also a good approach for small arrays. For large arrays, sorting may prove a performance issue so choose wisely.

In a sorted array, the min and max items will be at the start and the end of the array.

Arrays.sort(items); max = items[items.length - 1]; //100 min = items[0]; //0

This is the most basic version of the solution. The pseudo-code is :

Initialize the max and min with first item in the array Iterate the array from second position (index 1) Compare the ith item with max and min if current item is greater than max set max = current item elseif current item is lower than min set min = current item

After the loop finishes, the max and min variable will be referencing the largest and the smallest item in the array.

max = items[0]; min = items[0]; for (int i = 1; i < items.length; i++) < if (items[i] >max) < max = items[i]; >else if (items[i] < min) < min = items[i]; >> System.out.println(max); //100 System.out.println(min); //0

Recursion gives better performance for a big-size unsorted array. Note that we are writing the recursive call for max and min items, separately. If we need to find both items in a single invocation, we will need to change the program as per demand.

This solution is basically Divide and Conquer algorithm where we only handle the current index and the result of the rest (the recursive call) and merge them together for the final output.

For getting the maximum of items, at each item, we return the larger of the current items in comparison and all of the items with a greater index. A similar approach is for finding the minimum item.

min = getMax(items, 0, items[0]); //0 min = getMin(items, 0, items[0]); //100 public static int getMax(final int[] numbers, final int a, final int n) < return a >= numbers.length ? n : Math.max(n, getMax(numbers, a + 1, numbers[a] > n ? numbers[a] : n)); > private static int getMin(final int[] numbers, final int a, final int n)

In this short Java tutorial, we learned the different ways to find the maximum and the minimum element from an Array in Java. We learned to use the Stream API, Collections API, simple iterations, and advanced techniques such as recursion.

For smaller arrays, we should prefer the code readability and use the Stream or Collection APIs. For large arrays, where we will get noticeable performance improvements, using recursion can be considered.

Источник

Найдите максимальное число в массиве в Java

Найдите максимальное число в массиве в Java

  1. Найти максимальное число в массиве итеративным способом
  2. Найти максимальное число в массиве с помощью Stream
  3. Найти максимальное число в массиве с помощью Arrays.sort()

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

Найти максимальное число в массиве итеративным способом

Этот метод — традиционный способ найти максимальное число из массива. Он включает итератор, который используется для просмотра каждого элемента в массиве. Ниже у нас есть массив целых чисел intArray ; Сначала мы создаем переменную maxNum и инициализируем ее первым элементом intArray .

Мы создаем расширенный цикл for, который принимает массив и возвращает каждый элемент в каждой итерации. Затем мы проверяем каждый элемент с помощью maxNum , который имеет 24, и, как только он находит число больше 24, он заменяет 24 этим числом в maxNum . Он заменит число в maxNum , пока не достигнет конца массива; в противном случае он не нашел большего числа, чем существующее значение в maxNum .

public class ArrayMax   public static void main(String[] args)   int[] intArray = 24, 2, 0, 34, 12, 110, 2>;   int maxNum = intArray[0];   for (int j : intArray)   if (j > maxNum)  maxNum = j;  >   System.out.println("Maximum number = " + maxNum);  > > 

Найти максимальное число в массиве с помощью Stream

В Java 8 появился Stream API , который предоставляет несколько полезных методов. Один из них — метод Arrays.stream() , который принимает массив и возвращает последовательный поток. В нашем случае у нас есть массив типа int , и когда мы передаем его в поток, он возвращает IntStream .

Функция IntStream имеет метод max() , который помогает найти максимальное значение в потоке. Он возвращает OptionalInt , который описывает, что поток также может иметь пустые значения int .

Наконец, поскольку нам нужно максимальное число в виде int , мы будем использовать метод optionalInt.getAsInt() , который возвращает результат в виде типа int .

import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream;  public class ArrayMax   public static void main(String[] args)   int[] intArray = 24, 2, 0, 34, 12, 11, 2>;   IntStream intStream = Arrays.stream(intArray);  OptionalInt optionalInt = intStream.max();  int maxAsInt = optionalInt.getAsInt();   System.out.println("Maximum number = " + maxAsInt);  > > 

Найти максимальное число в массиве с помощью Arrays.sort()

Последний метод в этом списке использует метод сортировки, который организует массив в порядке возрастания. Для сортировки массива мы используем функцию Arrays.sort() и передаем intArray в качестве аргумента.

Чтобы увидеть, как массив будет выглядеть после операции сортировки, распечатываем его. Теперь, когда массив отсортирован и наибольшее число из всех находится в крайней левой позиции, мы получаем его позицию с помощью функции intArray.length — 1 , которая находится в последней позиции массива.

import java.util.Arrays;  public class ArrayMax   public static void main(String[] args)   int[] intArray = 24, 340, 0, 34, 12, 10, 20>;   Arrays.sort(intArray);   System.out.println("intArray after sorting: " + Arrays.toString(intArray));   int maxNum = intArray[intArray.length - 1];  System.out.println("Maximum number = " + maxNum);  > > 
intArray after sorting: [0, 10, 12, 20, 24, 34, 340] Maximum number = 340 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Сопутствующая статья — Java Array

Copyright © 2023. All right reserved

Источник

Как найти максимальный элемент массива java

Чтобы найти максимальный элемент массива в Java, можно пойти разными путями. Можно перебрать массив при помощи цикла или использовать стримы, как наиболее лаконичный вариант решения. Для примера найдем максимальный элемент массива, используя стримы. При помощи статического метода stream() класса Arrays преобразуем массив в стрим и найдем его максимум:

import java.util.Arrays; int[] coll = 1, 2, 8, 4, -2>; Arrays.stream(coll).max().getAsInt(); // 8 

Источник

Как найти максимальное число в массиве java

В Java 8 и выше можно использовать потоки streams для нахождения максимального числа в массиве. Для этого можно использовать метод max() класса java.util.stream.IntStream , который возвращает максимальное значение в потоке.

int[] numbers = 10, 20, 30, 40, 50>; int max = Arrays.stream(numbers).max().getAsInt(); System.out.println("Максимальное число: " + max); 

Здесь мы создаем поток из массива numbers с помощью метода Arrays.stream() , а затем вызываем метод max() для нахождения максимального значения. Метод max() вернет объект OptionalInt , поэтому мы вызываем метод getAsInt() для получения примитивного значения int

Чтобы найти максимальное число в массиве, можно использовать цикл для прохода по всем элементам и сравнения каждого элемента с текущим максимальным значением. Начальное значение максимального элемента можно установить как первый элемент массива, а затем в цикле сравнивать оставшиеся элементы с текущим максимальным значением и обновлять максимальный элемент, если текущий элемент больше. Вот как можно реализовать эту логику:

public static int findMax(int[] arr)  int max = arr[0]; // начальное значение максимального элемента for (int i = 1; i  arr.length; i++)  if (arr[i] > max)  max = arr[i]; > > return max; > 

Этот метод принимает в качестве аргумента массив arr и возвращает максимальный элемент в массиве. Вы можете вызвать этот метод и передать ему ваш массив для нахождения максимального значения.

Источник

Читайте также:  Python tkinter label параметры
Оцените статью