Find the Extreme elements in a List in Java

Java 8Object Oriented ProgrammingProgramming

The extreme elements in a list are the maximum and minimum elements. These can be obtained using the java.util.Collections.max() and java.util.Collections.min() methods respectively.

The Collections.max() method contains a single parameter i.e. the list whose maximum element is to be found and it returns the maximum element from the list. The Collections.min() method contains a single parameter i.e. the list whose minimum element is to be found and it returns the minimum element from the list.

A program that demonstrates this is given as follows:

Example

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) { 
      { 6, 2, 4, 9, 7 };
      List l = Arrays.asList(arr);
      System.out.println("The maximum element of the List is: " + Collections.max(l));
      System.out.println("The minimum element of the List is: " + Collections.min(l));
   }
}

The output of the above program is as follows:

The maximum element of the List is: 9
The minimum element of the List is: 2

Now let us understand the above program.

First, an Integer array arr[] is defined. Then a List is created from the array using the java.util.Arrays.asList() method. The maximum and minimum elements of the List are obtained using the Collections.max() and Collections.min() methods respectively. A code snippet which demonstrates this is as follows:

{ 6, 2, 4, 9, 7 };
List l = Arrays.asList(arr);
System.out.println("The maximum element of the List is: " + Collections.max(l));
System.out.println("The minimum element of the List is: " + Collections.min(l));
raja
Published on 07-Feb-2019 12:56:55
Advertisements