Get Maximum Value with Comparator in Java



In Java, the Comparator interface is used to define a custom ordering for objects in various Collections. This can be particularly useful when you need to find the maximum or minimum element based on specific criteria rather than natural ordering. One common use case is finding the maximum value in a collection using a comparator.

Java provides the Collections utility class, which includes the max() and min() methods that accept a comparator to perform customized comparisons. In this article, we will explore how to use these methods to find the maximum value from a list using a comparator.

Finding Maximum Value in a List

Utilize a comparator to identify the maximum element within a list, approached in reverse order. This method allows for a comprehensive evaluation of the elements, ensuring a thorough analysis.

Array and List: An array of integers is created and converted into a list using Arrays.asList().

List list = Arrays.asList(arr);

Comparator: The Collections.reverseOrder() method is used to create a comparator that sorts in reverse (descending) order.

Comparator comp = Collections.reverseOrder();

Finding Maximum: The Collections.min() method is called with the list and comparator. Although the method is named min(), it uses the reverse comparator, effectively giving the maximum value in descending order.

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

Example

Below is an example of finding the Maximum value in a list using the comparator ?

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 = 90

Time Complexity: Sorting the list with a comparator generally takes O(nlog?n), where n is the number of elements in the list.
Space Complexity: The space complexity is O(n) due to the list that stores the elements.

Find Maximum in Custom Objects

In this example, we will find the maximum value in a list of custom objects, such as Person objects. We'll use a comparator to sort by age and then find the oldest person.

  • Custom Object Person: We define a Person class with attributes name and age. The toString() method provides a readable output format.
  • Comparator: We use the Comparator.comparingInt() method to create a comparator that compares Person objects based on their age.
  • Finding Maximum: The Collections.max() method is used with the list of people and the age comparator to find the oldest person.

Example

Below is an example of finding the Maximum in custom objects using the comparator ?

import java.util.Collections;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return name + " (" + age + " years)";
    }
}
public class Demo {
    public static void main(String[] args) {
        Person p1 = new Person("John", 25);
        Person p2 = new Person("Alice", 30);
        Person p3 = new Person("Bob", 22);
        List<Person> people = Arrays.asList(p1, p2, p3);
        // Comparator to sort by age in ascending order
        Comparator<Person> ageComparator = Comparator.comparingInt(person -> person.age);
        // Finding the oldest person
        Person oldestPerson = Collections.max(people, ageComparator);
        System.out.println("Oldest person: " + oldestPerson);
    }
}

Output

Oldest person: Alice (30 years)

Time Complexity: Sorting the list with a comparator generally takes O(nlog?n), where n is the number of elements in the list.

Space Complexity: The space complexity is O(n) due to the list that stores the elements.

Conclusion

Using a Comparator in Java allows for flexible and powerful sorting and comparison operations. Whether you're working with simple data types or custom objects, comparators give you fine-grained control over how elements are compared. The examples provided demonstrate how to use Collections.max() and Collections.min() with comparators to find the maximum or minimum elements in different scenarios.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-26T20:42:05+05:30

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements