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

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

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

Массив содержит данные аналогичного типа. Хотя вы уже можете прочитать все элементы и выполнить с ними несколько операций, в этой статье показано, как найти максимальное значение в массиве в 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).

В этом посте будет обсуждаться, как найти минимальный и максимальный элемент в массиве в Java.

1. Использование списка

Если данный массив не является примитивным массивом, мы можем использовать Arrays.asList() который возвращает список, поддерживаемый массивом. Затем мы вызываем min() а также max() методы Collections class для получения минимального и максимального элементов соответственно. Обратите внимание, что при этом не выполняется фактическое копирование элементов массива.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

class Main

{

    public static void main(String[] args)

    {

        // не примитивный целочисленный массив

        Integer[] A = { 6, 8, 3, 5, 1, 9 };

        List<Integer> ints = Arrays.asList(A);

        System.out.println(“Min element is “ + Collections.min(ints));

        System.out.println(“Max element is “ + Collections.max(ints));

    }

}

Скачать  Выполнить код

 
Для примитивных массивов мы можем использовать Java 8 Stream для преобразования массива в список.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

import java.util.stream.Collectors;

class Main

{

    public static void main(String[] args)

    {

        // примитивный целочисленный массив

        int[] A = { 6, 8, 3, 5, 1, 9 };

        List<Integer> ints = Arrays.stream(A)

                                .boxed()

                                .collect(Collectors.toList());

        System.out.println(“Min element is “ + Collections.min(ints));

        System.out.println(“Max element is “ + Collections.max(ints));

    }

}

Скачать  Выполнить код

2. Использование библиотеки Guava

В библиотеке Guava есть Ints, Doubles, Chars, Longsи т. д., классы, предлагающие несколько статических служебных методов, относящихся к примитивам, которых еще нет ни в одном из них. Integer или же Arrays учебный класс. Чтобы найти минимальный и максимальный элемент, мы можем использовать min() а также max() методы соответствующего класса.

import com.google.common.primitives.Ints;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        System.out.println(“Min element is “ + Ints.min(A));

        System.out.println(“Max element is “ + Ints.max(A));

    }

}

Скачать код

3. Использование потока Java 8

С появлением Stream в Java 8 мы можем преобразовать массив в поток соответствующего типа, используя метод Arrays.stream() метод. Тогда мы можем вызвать max() а также min() метод, который возвращает максимальный и минимальный элемент этого потока как OptionalInt.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.Arrays;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        int max = Arrays.stream(A)

                        .max()

                        .getAsInt();

        int min = Arrays.stream(A)

                        .min()

                        .getAsInt();

        System.out.println(“Min element is “ + min);

        System.out.println(“Max element is “ + max);

    }

}

Скачать  Выполнить код

 
Мы также можем получить поток без использования Arrays.stream() метод, как показано ниже. Здесь идея состоит в том, чтобы получить поток индексов массива и сопоставить каждый индекс с соответствующим элементом в массиве.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import java.util.stream.IntStream;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        int max = IntStream.range(0, A.length)

                        .map(i -> A[i])

                        .max()

                        .getAsInt();

        int min = IntStream.range(0, A.length)

                        .map(i -> A[i])

                        .min()

                        .getAsInt();

        System.out.println(“Min element is “ + min);

        System.out.println(“Max element is “ + max);

    }

}

Скачать  Выполнить код

 
Наконец, мы можем назвать summaryStatistics() метод для потока числовых значений, который возвращает IntSummaryStatistics описывающие различные сводные данные об элементах этого потока. Чтобы получить минимальный и максимальный элемент, вызовите getMin() а также getMax() методы на нем.

import java.util.Arrays;

import java.util.IntSummaryStatistics;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        IntSummaryStatistics stats = Arrays.stream(A).summaryStatistics();

        System.out.println(“Min element is “ + stats.getMin());

        System.out.println(“Max element is “ + stats.getMax());

    }

}

Скачать  Выполнить код

 
Это эквивалентно:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import java.util.IntSummaryStatistics;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        IntSummaryStatistics stats = new IntSummaryStatistics();

        for (int i : A) {

            stats.accept(i);

        }

        System.out.println(“Min element is “ + stats.getMin());

        System.out.println(“Max element is “ + stats.getMax());

    }

}

Скачать  Выполнить код

4. Напишите свой собственный служебный метод

Мы также можем написать нашу собственную процедуру для поиска минимального и максимального элемента в массиве, как показано ниже:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

class Main

{

    private static int getMax(int[] A)

    {

        int max = Integer.MIN_VALUE;

        for (int i: A) {

            max = Math.max(max, i);

        }

        return max;

    }

    private static int getMin(int[] A)

    {

        int min = Integer.MAX_VALUE;

        for (int i: A) {

            min = Math.min(min, i);

        }

        return min;

    }

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        System.out.println(“Min element is “ + getMin(A));

        System.out.println(“Max element is “ + getMax(A));

    }

}

Скачать  Выполнить код

5. Использование сортировки

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

import java.util.Arrays;

class Main

{

    public static void main(String[] args)

    {

        int[] A = { 6, 8, 3, 5, 1, 9 };

        Arrays.sort(A);

        System.out.println(“Min element is “ + A[0]);

        System.out.println(“Max element is “ + A[A.length 1]);

    }

}

Скачать  Выполнить код

Это все о поиске минимального и максимального элементов в массиве в Java.

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

Добавить комментарий