How To Find Minimum And Maximum Values In An Arraylist In Java

How To Find Minimum And Maximum Values In An Arraylist In Java By iterating over ArrayList values

SOURCE CODE

MaximumAndMinimumValuesInArrayList.java

/*
 * How To Find Minimum And Maximum Values In An Arraylist In Java By iterating over ArrayList values.
 * https://mauricemuteti.info/how-to-find-minimum-and-maximum-values-in-an-arraylist-in-java/
 */
package maximumandminimumvaluesinarraylist;

import java.util.ArrayList;

/**
 *
 * @author Authentic
 */
public class MaximumAndMinimumValuesInArrayList {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        //ArrayList Of Numbers.
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(500);
        numbers.add(600);
        numbers.add(6000);
        numbers.add(700);
        numbers.add(300);
        numbers.add(200);
        numbers.add(900);
        numbers.add(2000);
        numbers.add(10);
        numbers.add(50);
        numbers.add(100);
        numbers.add(400);

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

        //Iterating over an arraylist using for loop to get the maximum value.
        for (int i = 0; i < numbers.size(); i++) {
            if (numbers.get(i) > max) {
                max = numbers.get(i);
            }
        }

        //Iterating over an arraylist using for loop to get the minimum value.
        for (int i = 0; i < numbers.size(); i++) {
            if (numbers.get(i) < min) {
                min = numbers.get(i);
            }
        }

        System.out.println("The Maximum Value Is : " + max);
        System.out.println("The Minimum Value Is : " + min);
    }

}

NETBEANS 8.2 IDE OUTPUT

run:
The Maximum Value Is : 6000
The Minimum Value Is : 10
BUILD SUCCESSFUL (total time: 0 seconds)

VIDEO TUTORIAL

Leave a Reply

Your email address will not be published. Required fields are marked *