- Найти максимальное число в массиве итеративным способом
- Найти максимальное число в массиве с помощью
Stream
- Найти максимальное число в массиве с помощью
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
If you are looking for the quickest and simplest way to perform various actions in regards to arrays, the use of the Collections class is extremely helpful (documentation available from https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html), actions ranges from finding the maximum, minimum, sorting, reverse order, etc.
A simple way to find the maximum value from the array with the use of Collections:
Double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4, 8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2, 3.5, 3.0, 1.1, 6.5, 5.1, -1.2, -5.1, 2.0, 5.2, 2.1};
List<Double> a = new ArrayList<Double>(Arrays.asList(decMax));
System.out.println("The highest maximum for the December is: " + Collections.max(a));
If you are interested in finding the minimum value, similar to finding maximum:
System.out.println(Collections.min(a));
The simplest line to sort the list:
Collections.sort(a);
Or alternatively the use of the Arrays class to sort an array:
Arrays.sort(decMax);
However the Arrays class does not have a method that refers to the maximum value directly, sorting it and referring to the last index is the maximum value, however keep in mind sorting by the above 2 methods has a complexity of O(n log n).
A solution with reduce()
:
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
In the code above, reduce()
returns data in Optional
format, which you can convert to int
by getAsInt()
.
If we want to compare the max value with a certain number, we can set a start value in reduce()
:
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
In the code above, when reduce()
with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
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.
1.1. Stream.max() and Stream.min()
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
1.2. IntStream.summaryStatistics()
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)));
3. Sorting the Array
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
4. Iterating the Array
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
5. Recursion
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) {
return a == numbers.length ? n
: Math.min(n, getMin(numbers, a + 1, numbers[a] < n ? numbers[a] : n));
}
6. Conclusion
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.
Happy Learning !!
Sourcecode on Github
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using “aslist()“. aslist() type casts a list from the array passed in its argument. This function is defined in “Java.utils.Arrays“.
To get the minimum or maximum value from the array we can use the Collections.min() and Collections.max() methods.
But as this method requires a list type of data we need to convert the array to list first using above explained “aslist()” function.
Note: “The array you are passing to the Arrays.asList() must have a return type of Integer or whatever class you want to use”, since the Collections.sort() accepts ArrayList object as a parameter.
Note: If you use type int while declaring the array you will end up seeing this error: “no suitable method found for min(List<int[]>)”
Java
import
java.util.Arrays;
import
java.util.Collections;
public
class
MinNMax {
public
static
void
main(String[] args)
{
Integer[] num = {
2
,
4
,
7
,
5
,
9
};
int
min = Collections.min(Arrays.asList(num));
int
max = Collections.max(Arrays.asList(num));
System.out.println(
"Minimum number of array is : "
+ min);
System.out.println(
"Maximum number of array is : "
+ max);
}
}
Output
Minimum number of array is : 2 Maximum number of array is : 9
This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Last Updated :
21 Jun, 2022
Like Article
Save Article