You can find the smallest value of an ArrayList using the following ways in JAVA ARRAY List:
way 1. Find the smallest value of an ArrayList using the Collection class.
- you are available with a collection class named min.
- 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> min(Collection<? extends T> c)
Example
package com.javacodeexamples.collections.arraylist;
import java.util.ArrayList;
import java.util.Collections;
public class FindMinValueArrayListExample {
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) );
}
}
The output is :
ArrayList Min Value: 43
Way 2: Find the smallest value of an ArrayList using the for loop.
- You can make use of for loop instead of collections.
Example
package com.javacodeexamples.collections.arraylist;
import java.util.ArrayList;
public class FindMinValueArrayListExample {
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);
//declare min and max elements index as 0 (i.e. first element)
int minIndex = 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;
}
System.out.println("ArrayList Min Value is: "
+ min
+ ", Found at index: "
+ minIndex
);
}
}
The result is
ArrayList Min Value is: 43, Found at index: 3