Java Program to get maximum value with Comparator


First, declare an integer array and add some elements −

Integer arr[] = { 40, 20, 30, 10, 90, 60, 700 };

Now, convert the above array to List −

List list = Arrays.asList(arr);

Now, use Comparator and the reverseOrder() method. Using min() will eventually give you the minimum value, but with reverseOrder(), it reverses the result −

Comparator comp = Collections.reverseOrder();
System.out.println("Maximum element = "+Collections.min(list, comp));

Example

 Live Demo

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Demo {
   @SuppressWarnings("unchecked")
   public static void main(String args[]) {
      Integer arr[] = { 40, 20, 30, 10, 90, 60, 70 };
      List list = Arrays.asList(arr);
      Comparator comp = Collections.reverseOrder();
      System.out.println("Maximum element = "+Collections.min(list, comp));
   }
}

Output

Maximum element = 700

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements