How to find the maximum and minimum number in a List

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:15Smallest element in the list is:3

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set