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

В пакетике java.util.Collections есть уже готовые методы на такой случай. Они так и называются: max и min. Остается только воспользоваться ими. Например:

ArrayList<Integer> list = new ArrayList<>();
list.add(12);
list.add(21);
list.add(111);

System.out.println(Collections.max(list));
System.out.println(Collections.min(list));

Collection.max

Collection.min


Еще вариант стандартный: занести в переменные min и max первый элемент списка, затем проходить в цикле и сравнивать число на итерации с числом в переменных. Если оно меньше, чем min, то заносить его в min. Если больше, чем max — заносить в max.

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(-666);
list.add(666);

int min = list.get(0);
int max = list.get(0);

for (Integer i: list) {
    if(i < min) 
        min = i;
    if(i > max) 
        max = i;
}

System.out.println("минимальное число: " + min);
System.out.println("максимальное число: " + max);

Еще вариант: отсортировать список с помощью Collections.sort и затем у отсортированного списка взять первый и последний элементы соответственно:

Collections.sort(list);

System.out.println(list.get(0));
System.out.println(list.get(list.size() - 1));

Есть и другие варианты, но этого тоже должно хватить.

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 для начинающих заключается в написании Java-программы, которая принимает данные от пользователя, находит максимальное и минимальное число и выводит их на консоль.

    Цель этой статьи – научить получать данные от пользователя и использовать класс java.lang.Math для выполнения некоторых математических операций, например, чтобы найти максимальное и минимальное значения в Java.

    Также есть другие 4 способа, которые с примерами кода даны ниже.

    Мы можем использовать класс Scanner, добавленный в Java 1.5, для чтения пользовательского ввода с консоли. Сканеру нужен InputStream для чтения данных, и поскольку мы читаем с консоли, мы можем передать System.in, который является InputStream для консоли Eclipse, или командную строку в зависимости от того, что используется.

    Этот класс также помогает преобразовать пользовательский ввод в требуемый тип данных, например если пользователь вводит числа, необходимо затем преобразовать их в тип данных int и сохранить их в переменной int. Можно использовать метод nextInt(), чтобы считать пользовательский ввод как Integer.

    Точно так же можно использовать nextLine() для чтения ввода пользователя как String. Есть другие методы, доступные для чтения с плавающей точкой, двойного или логического значения из командной строки.

    Как только получены оба числа, просто нужно использовать оператор отношения меньше и больше, чтобы найти наименьшее и наибольшее число.

    После этого можно использовать Math.max(), чтобы узнать максимум двух чисел, он должен совпадать с предыдущим результатом.

    Максимум и минимум на примере

    Пример программы состоит из двух частей. В первой части мы принимаем данные от пользователя, используем if block и реляционный оператор, чтобы найти максимальное значение в Java, и далее используем метод Math.max() для той же цели.

    Во второй части программы мы попросим пользователя ввести еще два числа, а затем мы используем if блок, чтобы вычислить меньшее из двух. После этого мы снова используем функцию Math.min() для вычисления минимального числа. Если наша программа правильная, то оба результата должны быть выведены одинаковыми.

    Мы можем запустить эту программу из Eclipse IDE, просто скопировав код после создания проекта. Eclipse автоматически создаст исходный файл с тем же именем, что и открытый класс, и поместит его в нужный пакет. Кроме того, также можно запустить эту программу из командной строки, следуя приведенным здесь шагам.

    нахождение максимального и минимального значения

    import java.util.Scanner; 
    import java.util.concurrent.Semaphore; 
    import java.util.concurrent.locks.Condition; 
    import java.util.concurrent.locks.Lock; 
    import java.util.concurrent.locks.ReentrantLock;
    public class MaxMinExerciseInJava {
     public static void main(String args[]) throws InterruptedException { 
      Scanner scnr = new Scanner(System.in);
      // вычисляем максимум 2 чисел 
      System.out.println("Введите 2 числа");
      int a = scnr.nextInt(); 
      int b = scnr.nextInt();
      if (a > b) {
        System.out.printf("Between %d and %d, maximum is %d %n", a, b, a);
      } else {
        System.out.printf("Between %d and %d, maximum number is %d %n", a, b, b);
      }
      int max = Math.max(a, b);
      System.out.printf("Maximum value of %d and %d using Math.max() is %d %n", a, b, max);
      int x = scnr.nextInt(); 
      int y = scnr.nextInt();
    
      if (x < y) {
        System.out.printf("Between %d and %d, Minimum Number is %d %n", x, y, x);
      } else {
        System.out.printf("Between %d and %d, Minimum is %d %n", x, y, y); 
      }
      
      int min = Math.min(x, y);
    
      System.out.printf("Maximum value of %d and %d using Math.min() is %d %n", x, y, min)
     }
    
    }
    

    Вывод:
    введите 2 числа
    10
    11
    Between 10 and 11, maximum number is 11
    Maximum value of 10 and 11 using Math.max() is 11
    Please enter two numbers to find minimum of two
    45
    32
    Between 45 and 32, Minimum is 32
    Maximum value of 45 and 32 using Math.min() is 32

    Из массива int

    В этом примере мы находим максимальные и минимальные значения элемента из массива int на Java.

    Читайте также как найти сумму и среднее значение элементов массива на Java

    class MinMaxExample { 
     
      public static void main(String args[]){
        int array[] = new int[]{10, 11, 88, 2, 12, 120};
     
        // Вызов метода getMax () для получения максимального значения
        int max = getMax(array);
        System.out.println("Maximum Value is: "+max);
     
        // Вызов метода getMin () для получения минимального значения
        int min = getMin(array);
        System.out.println("Minimum Value is: "+min);
      }
     
      //здесь находим максимум
      public static int getMax(int[] inputArray){ 
        int maxValue = inputArray[0]; 
        for(int i=1;i < inputArray.length;i++){ if(inputArray[i] > maxValue){ 
             maxValue = inputArray[i]; 
          } 
        } 
        return maxValue; 
      }
     
      // здесь находим минимум
      public static int getMin(int[] inputArray){ 
        int minValue = inputArray[0]; 
        for(int i=1;i<inputArray.length;i++){ 
          if(inputArray[i] < minValue){ 
            minValue = inputArray[i]; 
          } 
        } 
        return minValue; 
      } 
    }

    Вывод:
    Maximum Value is: 120
    Minimum Value is: 2

    Методы max и min

    В пакете java.util.Collections есть методы max и min.

    ArrayList list = new ArrayList<>();
    list.add(12);
    list.add(21);
    list.add(111);
    
    System.out.println(Collections.max(list));
    System.out.println(Collections.min(list));

    Используя цикл

    Вносим в переменные min и max первый элемент из списка, запускаем цикл и сравниваем число на итерации с числом в переменных.

    Если оно меньше, чем min, то присваиваем его min, иначе если больше, чем max — то это max.

    ArrayList list = new ArrayList();
    list.add(100);
    list.add(-666);
    list.add(666);
    
    int min = list.get(0);
    int max = list.get(0);
    
    for (Integer i: list) {
        if(i < min) min = i; if(i > max) 
            max = i;
    }
    
    System.out.println("минимальное число: " + min);
    System.out.println("максимальное число: " + max);

    С помощью Collections.sort взять первый и последний из списка

    Отсортируем список с помощью Collections.sort, теперь в этом списке первый элемент – это maximum,а последний будет minimum:

    Collections.sort(list);
    
    System.out.println(list.get(0));
    System.out.println(list.get(list.size() - 1));

    Introduction

    In this guide, we’ll take a look at how to get the maximum or minimum element in a Java Collection, both for primitive types and custom comparable objects, via their fields.

    Getting the Maximum or Minimum Element with Collections.max()

    The Collections framework provides us with a wide variety of helper, static methods for working with Collections in Java. It’s no wonder that this same framework allows us to search and return the maximum or minimum element of a collection as well.

    Collections.max() and Collections.min() with Primitive Types

    Working with primitive types is fairly easy in most regards, and as long as they’re Comparable – we can easily search through them.

    To find the maximum or minimum element of a Collection consisting of primitive types, we simply call the Collections.max() or Collections.min() methods, passing in the collections we’re searching in:

    List<Integer> list = List.of(1, 5, 4, 3, 7, 6, 9, 4);
            
    Integer min = Collections.min(list);
    Integer max = Collections.max(list);
    
    System.out.println(String.format("Minimum element is %s", min));
    System.out.println(String.format("Maximum element is %s", max));
    

    Running this code returns our maximum and minimum elements:

    Minimum element is 1
    Maximum element is 9
    

    Collections.max() and Collections.min() with Custom Objects

    Though, we rarely only work with just primitive types. Typically, we’ll be working with objects. Naturally, since these structures are much more complex – you get to decide what constitutes a greater element between the two.

    Usually, this is achieved by implementing the Comparable interface, which allows you to compare any two instances of a class to determine which is greater. Let’s define a class and make it Comparable:

    public class Book implements Comparable<Book> {
        private String author;
        private String name;
        private int pageNumber;
    
        // Constructor, getters and setters
    
        @Override
        public int compareTo(Book book) {
            return (this.pageNumber > book.pageNumber) ? 1 : -1;
        }
    
        @Override
        public String toString() {
            return "Book{" +
                    "author='" + author + ''' +
                    ", name='" + name + ''' +
                    ", pageNumber=" + pageNumber +
                    '}';
        }
    }
    
    

    You’ll have to @Override the compareTo() method and define by which criteria the entities are compared with. It’ll typically boil down to simple primitive types in the end, such as comparing the pageNumber attribute. We’ve also added a toString() method for convenient formatting.

    Now, searching for the maximum or minimum element, in a collection of custom objects is as easy as calling Collections.max() or Collections.min() on the Collection:

    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
    bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
    bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
    
    Book min = Collections.min(bookList);
    Book max = Collections.max(bookList);
    
    System.out.println(String.format("Minimum element is %s", min));
    System.out.println(String.format("Maximum element is %s", max));
    

    Given our comparison criteria, the results are:

    Minimum element is Book{author='Nick Bostrom', name='Superintelligence', pageNumber=352}
    Maximum element is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    

    Custom Comparator

    You can avoid making the Book comparable, if you can’t by supplying a new Comparator in the Collections calls. Though, this solution is verbose and best avoided/substituted with the techniques outlined after this.

    Nevertheless, it’s a fully valid way to compare entities and find the maximum/minimum value:

    Book min = Collections.min(bookList, new Comparator<Book>() {
        @Override
        public int compare(Book o1, Book o2) {
            return (o1.getPageNumber() > o2.getPageNumber()) ? 1 : -1;
        }
    });
    
    System.out.println(String.format("Minimum by page count is %s", min));
    

    Or, this can be shortened through a Lambda Expression:

    Book min = Collections.min(bookList, 
        (o1, o2) -> (o1.getPageNumber() > o2.getPageNumber()) ? 1 : -1);
    

    Getting the Maximum or Minimum Element with Stream.max() and Stream.min()

    With the advent of Java 8, we’ve been introduced to a wonderful Stream API that allows us to perform various processing pipelines. A Stream can find a maximum or minimum element via the max() or min() methods, leveraging either a new Comparator for the job, or using an already existing one, such as the comparator we’ve built-into our Book class.

    This allows you to have non-Comparable classes and quickly use a new Comparator to set the criteria using any field. This flexibility is what makes Streams so amazing for processing data.

    Stream.max() and Stream.min() with Primitive Types

    Let’s start off with a simple Collection of primitive types. To get the maximum or minimum element of the collection, we stream() it and call the min() or max() methods:

    List<Integer> list = List.of(1, 5, 4, 3, 7, 6, 9, 4);
    Integer maxInt = list.stream().mapToInt(i -> i).max().getAsInt();
    Integer minInt = list.stream().mapToInt(i -> i).min().getAsInt();
    
    System.out.println(String.format("Minimum element is %s", minInt));
    System.out.println(String.format("Maximum element is %s", maxInt));
    

    Instead of mapping i -> i, we could’ve alternatively just use:

    Integer maxInt = list.stream().mapToInt(Integer::intValue).max().getAsInt();
    

    The max() and min() methods return an Optional – or a derivative of the class, such as OptionalInt, OptionalDouble, etc. To extract the integer value – we use the getAsInt() at the end of the call chain.

    Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

    Running this code results in:

    Minimum element is 1
    Maximum element is 9
    

    Instead of mapToInt() you can also use a Comparator, such as comparing() or comparingInt() (both of which would produce the same output):

    Integer maxInt = list.stream().max(Comparator.comparing(Integer::intValue)).get();
    Integer minInt = list.stream().min(Comparator.comparingInt(Integer::intValue)).get();
    

    Again, these methods return an Optional, so we get() the result in the end. comparing() has the flexibility of comparing non-Integer values as well, but since we’re constraining ourselves to just Integers here, it doesn’t make any difference.

    Stream.max() and Stream.min() with Custom Objects

    Using custom comparators with custom objects is where Streams shine the most and where they provide the most flexibility. When using the Collections framework, we were constrained to compare the elements via the compareTo() method, overridden from the Comparable interface, if you don’t want to define a chunky new Comparator.

    With Streams – we can define a new Comparator on the fly with any field, without the class even having to implement the Comparable interface. Let’s find the maximum and minimum element of a collection with custom objects, using a custom comparator and streams:

    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
    bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
    bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
    
    // Using native compareTo() Method
    Book min = bookList.stream().min(Book::compareTo).get();
    Book max = bookList.stream().max(Book::compareTo).get();
    
    // Using custom new Comparator
    Book minByAuthor = bookList.stream().min(Comparator.comparing(Book::getAuthor)).get();
    Book maxByAuthor = bookList.stream().max(Comparator.comparing(Book::getAuthor)).get();
    
    System.out.println(String.format("Minimum by page count is %s", min));
    System.out.println(String.format("Maximum by page count is %s", max));
    
    System.out.println(String.format("Minimum by author is %s", minByAuthor));
    System.out.println(String.format("Maximum by author is %s", maxByAuthor));
    

    This time around, we can use any field and supply it to the Comparator.comparing() method. You can also use alternative methods, such as comparingInt() here, but since we’re comparing the lexicographical value of Strings, we’ll be sticking with the generic comparing() method.

    Running this code results in:

    Minimum by page count is Book{author='Nick Bostrom', name='Superintelligence', pageNumber=352}
    Maximum by page count is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    
    Minimum by author is Book{author='Max Tegmark', name='Our Mathematical Universe', pageNumber=432}
    Maximum by author is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    

    Using a for Loop

    Finally, the good old for loop can be used to search for a maximum or minimum element:

    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
    bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
    bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
    
    List<Integer> intList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
    
    // Instantiate as the first book initially
    Book maxBook = bookList.get(0);
    Integer maxInt = 0;
    
    for (Book book : bookList) {
        // book.getPageNumber() < minBook.getPageNumber()
        if (book.getPageNumber() > maxBook.getPageNumber()) {
            maxBook = book;
        }
    }
    
    for (Integer integer : intList) {
        // integer < minInt
        if (integer > maxInt) {
            maxInt = integer;
        }
    }
    
    System.out.println(String.format("Maximum by page count is %s", maxBook));
    System.out.println(String.format("Maximum int is %s", maxInt));
    

    This results in the same results we’ve been seeing so far:

    Maximum by page count is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    Maximum int is 9
    

    Conclusion

    In this guide, we’ve taken a look at how to find the maximum and minimum elements of a Java Collection. We’ve taken a look at both primitive types and custom objects, default and custom comparators, and best practices, including a manual for loop.

    Find Minimum Maximum value in ArrayList Java example shows how to find the minimum and maximum value in ArrayList. The example also shows how to find minimum maximum value along with index in Java ArrayList.

    There are a couple of ways to find minimum and maximum value in Java ArrayList.

    1) Find Min Max value in ArrayList using Collections class

    You can use min and max methods of Collections class.

    static <T extends Object & Comparable<? super T>  min(Collection<? extends T> c)

    This method returns the minimum element/value of the specified collection according to the natural ordering of the elements.

    static <T extends Object & Comparable<? super T>  max(Collection<? extends T> c)

    This method returns the maximum element/value of the specified collection according to the natural ordering of the elements.

    Example

    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

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    package com.javacodeexamples.collections.arraylist;

    import java.util.ArrayList;

    import java.util.Collections;

    public class FindMinMaxValueArrayListExample {

        public static void main(String[] args) {

            /*

             * ArrayList containing student marks

             */

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

            //add elements to ArrayList

            aListMarks.add(53);

            aListMarks.add(67);

            aListMarks.add(89);

            aListMarks.add(43);

            aListMarks.add(87);

            aListMarks.add(71);

            aListMarks.add(63);

            aListMarks.add(45);

            aListMarks.add(69);

            aListMarks.add(53);

            /*

             * To find minimum value in ArrayList, use

             * min method of Collections class.

             */

            System.out.println( “ArrayList Min Value: “ + Collections.min(aListMarks) );

            /*

             * To find maximum value in ArrayList, use

             * max method of Collections class.

             */

            System.out.println( “ArrayList Max Value: “ + Collections.max(aListMarks) );

        }

    }

    Output

    ArrayList Min Value: 43

    ArrayList Max Value: 89

    How to find an index of minimum maximum elements in Java ArrayList?

    If you want to find index of minimum or maximum element instead of value, you can use indexOf method of the ArrayList class.

    This method returns the index of the specified element. If the element is not found in the ArrayList, it returns -1.

    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

    31

    32

    33

    34

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

    //add elements to ArrayList

    aListMarks.add(53);

    aListMarks.add(67);

    aListMarks.add(89);

    aListMarks.add(43);

    aListMarks.add(87);

    aListMarks.add(71);

    aListMarks.add(63);

    aListMarks.add(45);

    aListMarks.add(69);

    aListMarks.add(53);

    /*

    * To find minimum value in ArrayList, use

    * min method of Collections class.

    *

    * To get the index of an element, use indexOf method.

    */

    System.out.println( “ArrayList Min Value is at index: “

                        + aListMarks.indexOf(Collections.min(aListMarks)) );

    /*

    * To find maximum value in ArrayList, use

    * max method of Collections class.

    * To get the index of an element, use indexOf method.

    */

    System.out.println( “ArrayList Max Value is at index: “

            + aListMarks.indexOf(Collections.max(aListMarks)) );

    Output

    ArrayList Min Value is at index: 3

    ArrayList Max Value is at index: 2

    2) Find Min Max value in ArrayList using for loop

    If you want to find min max values without using the Collections class, you can use for loop to find the same as given below.

    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

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    package com.javacodeexamples.collections.arraylist;

    import java.util.ArrayList;

    public class FindMinMaxValueArrayListExample {

        public static void main(String[] args) {

            /*

             * ArrayList containing student marks

             */

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

            //add elements to ArrayList

            aListMarks.add(53);

            aListMarks.add(67);

            aListMarks.add(89);

            aListMarks.add(43);

            aListMarks.add(87);

            aListMarks.add(71);

            aListMarks.add(63);

            aListMarks.add(45);

            aListMarks.add(69);

            aListMarks.add(53);

            //declare min and max value as the first element of the list

            int min = aListMarks.get(0);

            int max = aListMarks.get(0);

            //declare min and max elements index as 0 (i.e. first element)

            int minIndex = 0, maxIndex = 0;

            //Iterate through ArrayList

            for(int i = 1; i < aListMarks.size(); i++ ){

                 /*

                  * If current value is less than min value, it

                  * is new minimum value

                  */

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

                    min = aListMarks.get(i);

                    minIndex = i;

                }

                 /*

                  * If current value is greater than max value, it

                  * is new maximum value.

                  */

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

                    max = aListMarks.get(i);

                    maxIndex = i;

                }

            }

            System.out.println(“ArrayList Min Value is: “

                                + min

                                + “, Found at index: “

                                + minIndex

                    );

            System.out.println(“ArrayList Max Value is: “

                                + max

                                + “, Found at index: “

                                + maxIndex

                    );

        }

    }

    Output

    ArrayList Min Value is: 43, Found at index: 3

    ArrayList Max Value is: 89, Found at index: 2

    This example is a part of the Java ArrayList tutorial with examples.

    Please let me know your views in the comments section below.

    About the author

    • Author
    • Recent Posts

    Rahim

    I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

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