Collections FrameworkJava-Collection-Examples

How to find the maximum and minimum number in a List

Posted On
Posted By admin

In this blog post, I will be demonstrating how you can find the largest and smallest number in an array. Consider the following code snippet:


package learnjava.collections;

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

public class MaxMinDemo {

public static void main(String[] args) {
List<Integer> input = new ArrayList<Integer>();
input.add(3);
input.add(9);
input.add(5);
input.add(15);
input.add(11);

System.out.println("Biggest element in the list is:"+Collections.max(input));
System.out.println("Smallest element in the list is:"+Collections.min(input));

}
}

 

This code uses the Collections.max and Collections.min methods. The Collections class contains static utility methods that operate on collections like List, Set etc.  The Collections.max method returns the greatest element in the list according to the natural order or sorting. Similarly, the Collections.min returns the smallest element in the list according to the natural order of sorting. When this code is executed, it will print the following output:

Biggest element in the list is:15
Smallest element in the list is:3
If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

One thought on “How to find the maximum and minimum number in a List
  1. how to

    Awesome article.

leave a Comment