How To Find Minimum And Maximum Values In An Arraylist In Java Using Collections Sort

How To Find Minimum And Maximum Values In An Arraylist In Java Using Collections Sort

SOURCE CODE

MaximumAndMinimumValuesInAnArrayListCollectionSort.java

/*
 * How To Find Minimum And Maximum Values In An Arraylist In Java Using Collections Sort.
 * https://mauricemuteti.info/how-to-find-minimum-and-maximum-values-in-an-arraylist-in-java-using-collections-sort/
 */
package maximumandminimumvaluesinanarraylistcollectionsort;

import java.util.ArrayList;
import java.util.Collections;

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

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

        //Creating An ArrayList
        ArrayList<Integer> values = new ArrayList<>();
        //Adding Integer Values to An ArrayList.
        values.add(1000);
        values.add(500);
        values.add(700);
        values.add(1200);
        values.add(30000);

        System.out.println("ArrayList Elements Before Sorting");
        //Printing ArrayList Values On The console
        for (int i = 0; i < values.size(); i++) {
            System.out.println("Value At Index (" + i + ")" + values.get(i));
        }
        System.out.println("");
        //Using collections.sort 

        Collections.sort(values);

        System.out.println("ArrayList Elements After Sorting");
        //Printing ArrayList Values On The console
        for (int i = 0; i < values.size(); i++) {
            System.out.println("Value At Index (" + i + ")" + values.get(i));
        }

        System.out.println("");
        //Getting Minimun value.
        int min = values.get(0);
        System.out.println("The Minimum Value Is : " + min);
        //Getting Maximum value.
        int max = values.get(values.size() - 1);
        System.out.println("The Maximum Value Is : " + max);
    }

}

NETBEANS 8.2 OUTPUT

run:
ArrayList Elements Before Sorting
Value At Index (0)1000
Value At Index (1)500
Value At Index (2)700
Value At Index (3)1200
Value At Index (4)30000

ArrayList Elements After Sorting
Value At Index (0)500
Value At Index (1)700
Value At Index (2)1000
Value At Index (3)1200
Value At Index (4)30000

The Minimum Value Is : 500
The Maximum Value Is : 30000
BUILD SUCCESSFUL (total time: 1 second)

VIDEO TUTORIAL

Leave a Reply

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