tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collections > Advanced Min and Max

Advanced Min and Max 

The following example shows how to use Collections min and max API. It returns the minimum/maximum element of the given collection, according to the order induced by the specified comparator. Here the comparison function need not be implemented by the objects in the list. Java provides a custom comparison function known as Comparator. It is more useful when compared Comparable as we can provide only one comparison function with Comparable and the objects in the list need to implement Comparable interface. However with Comparator user can provide any number of comparison functions and the objects in the list need not implement this interface.

  • Collections.min()
  • Collections.max()

File Name  :  
com/bethecoder/tutorials/utils/collections/AdvancedCustomMinMax.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.collections;

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

public class AdvancedCustomMinMax {

  public static void main (String [] args) {
    
    List<Manager> workerList = Arrays.asList(new Manager [] {
        new Manager("ONE"90000),
        new Manager("TWO"280000),
        new Manager("NINE"1820000),
        new Manager("THREE"60000),
        new Manager("FOUR"300000),
        new Manager("FIVE"200000),
        new Manager("SIX"420000),
        new Manager("SEVEN"180000),
        new Manager("EIGHT"620000),
    });
    
    //Returns the maximum/minimum element of the given collection, 
    //according to the order provided by comparator
    System.out.println("Max Salaried Manager is " + Collections.max(workerList, new ManagerComparator()));
    System.out.println("Min Salaried Manager is " + Collections.min(workerList , new ManagerComparator()));
  }
}

class Manager {
  private String name;
  private int salary;
  
  public Manager(String name, int salary) {
    super();
    this.name = name;
    this.salary = salary;
  }
  
  public String toString() {
    return "Manager[" + name + ", " + salary + "]";
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int salary) {
    this.salary = salary;
  }
}

class ManagerComparator implements Comparator<Manager> {

  @Override
  public int compare(Manager first, Manager second) {
    return new Integer(first.getSalary()).compareTo(new Integer(second.getSalary()));
  }
  
}
   

It gives the following output,
Max Salaried Manager is Manager[NINE, 1820000]
Min Salaried Manager is Manager[THREE, 60000]



 
  


  
bl  br