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

В этом посте будет обсуждаться, как найти минимальный и максимальный элемент в массиве в 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.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The minimum value is the one with the smallest value and the maximum value is the one with the largest value. The main task here is to find the minimum and maximum value from the ArrayList. Consider an example of an ArrayList, and we need to find the largest and the smallest element. 

    Example:

    Input List: {10, 20, 8, 32, 21, 31};
    
    Output: 
    
    Maximum is: 32
    
    Minimum is: 8

    Method 1: By iterating over ArrayList values

    1. First, we need to initialize the ArrayList values.
    2. Then the length of the ArrayList can be found by using the size() function.
    3. After that, the first element of the ArrayList will be store in the variable min and max.
    4. Then the for loop is used to iterate through the ArrayList elements one by one in order to find the minimum and maximum from the array list.

    Java

    import java.util.*;

    public class Max {

        public static void main(String args[])

        {

            ArrayList<Integer> arr = new ArrayList<>();

            arr.add(10);

            arr.add(20);

            arr.add(8);

            arr.add(32);

            arr.add(21);

            arr.add(31);

            int min = arr.get(0);

            int max = arr.get(0);

            int n = arr.size();

            for (int i = 1; i < n; i++) {

                if (arr.get(i) < min) {

                    min = arr.get(i);

                }

            }

            for (int i = 1; i < n; i++) {

                if (arr.get(i) > max) {

                    max = arr.get(i);

                }

            }

            System.out.println("Maximum is : " + max);

            System.out.println("Minimum is : " + min);

        }

    }

    Output

    Maximum is : 32
    Minimum is : 8

    Method 2: Using Collection class Methods

    We can use the min() and max() method of the collection class of Java. Collections in java is basically a framework that provides an architecture to accumulate and handle the group of objects. Java Collection framework provides many classes such as ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet.

    Approach:

    1. First, we need to create a class.
    2. Then an integer ArrayList needs to be created to store the elements. After that, the length of the ArrayList should be calculated with the help of the size() method.
    3. The length of the ArrayList will be used to iterate through the loop and print the elements of the ArrayList.
    4. Then, the min and max method of collection class will be used to find the minimum and maximum from the ArrayList and will store in the min and max variable and then the result will be printed on the screen.

    Java

    import java.util.ArrayList;

    import java.util.Collections;

    public class MinMax {

        public static void main(String args[])

        {

            ArrayList<Integer> arr = new ArrayList<Integer>();

            arr.add(10);

            arr.add(20);

            arr.add(5);

            arr.add(8);

            int n = arr.size();

            System.out.println("ArrayList elements are :");

            for (int i = 0; i < n; i++) {

                System.out.print(arr.get(i) + " ");

            }

            System.out.println();

            int max = Collections.max(arr);

            System.out.println("Maximum is : " + max);

            int min = Collections.min(arr);

            System.out.println("Minimum is : " + min);

        }

    }

    Output

    Array elements are :
    10 20 5 8 
    Maximum is : 20
    Minimum is : 5

     Method 3: By sorting the ArrayList

    1. First, we need to import the Collections class, because in the Collections class there is a method called Collections.sort() which we need to sort the unsorted array.
    2. After that, the ArrayList of integers will be created and then we will calculate the length using size() function.
    3. Then, the ArrayList will be sorted using the predefined function, and by default, it will be sorted in increasing order only.
    4. For finding minimum and maximum values from the ArrayList, we simply need to find the first and last element of the ArrayList, because the ArrayList is sorted in ascending order then the first element will be the smallest and the last element will be largest among all of the elements.
    5. The first element can be found by using arr.get(0), because it is present in the first position and the index of the array is started from 0.
    6. The last element can be found by using arr.get(n-1), since n is the size of the array and array index is started from 0, that’s why we need to find the element that is in index n-1. Also, this is a sorted ArrayList then the largest element is present at the end.

    Java

    import java.util.*;

    import java.util.Collections;

    public class MaxMinSort {

        public static void main(String args[])

        {

            ArrayList<Integer> arr = new ArrayList<Integer>();

            arr.add(10);

            arr.add(12);

            arr.add(5);

            arr.add(8);

            arr.add(21);

            arr.add(16);

            arr.add(15);

            int n = arr.size();

            int i;

            System.out.println("Elements of the ArrayList : ");

            for (i = 0; i < n; i++) {

                System.out.print(arr.get(i) + " ");

            }

            System.out.println();

            Collections.sort(arr);

            System.out.println("ArrayList after sorting : ");

            for (i = 0; i < n; i++) {

                System.out.print(arr.get(i) + " ");

            }

            System.out.println();

            int min = arr.get(0);

            int max = arr.get(n - 1);

            System.out.println("Maximum is : " + max);

            System.out.println("Minimum is : " + min);

        }

    }

    Output

    Elements of the array : 
    10 12 5 8 21 16 15 
    Arrays after sorting : 
    5 8 10 12 15 16 21 
    Maximum is : 21
    Minimum is : 5

    Last Updated :
    15 Dec, 2020

    Like Article

    Save Article

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

    Пример:

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

    Результат:

    Минимальное число: 10
    

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

    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

  • Read
  • Discuss
  • 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

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