Как найти минимум массива java

По-всякому, например так:

    var nums = new int[] {1, 4, -2, 3};
    var min = Arrays.stream(nums).min();
    System.out.println(min.isPresent() ? min.getAsInt() : "empty array");

или так:

    var nums = new int[] {1, 4, -2, 3};
    var min = Collections.min(Arrays.stream(nums).boxed().collect(Collectors.toList()));
    System.out.println(min);

или так:

    var nums = new int[]{1, 4, -2, 3};
    var min = nums[0];
    for (int num : nums) {
        if (num < min) {
            min = num;
        }
    }
    System.out.println(min);

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

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

    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

    Понравилась статья? Поделить с друзьями:
  • Сокровища джека холла рдр2 как найти
  • Как составить уравнения реакций по химии 8 класс видеоурок
  • Как найти среднюю температуру холодного месяца
  • Как найти фото в галерее памяти
  • Как найти средний уклон пути