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

Custom 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 natural ordering of its elements. To sort a custom object listing, each object in it has to implement Comparable interface.

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

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

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

public class CollectionsCustomMinMax {

  public static void main (String [] args) {
    
    List<Employee> empList = Arrays.asList(new Employee [] {
        new Employee("ONE"240000),
        new Employee("TWO"280000),
        new Employee("THREE"120000),
        new Employee("FOUR"300000),
        new Employee("FIVE"200000),
        new Employee("SIX"420000),
        new Employee("SEVEN"180000),
        new Employee("EIGHT"620000),
        new Employee("NINE"820000),
    });
    
    //Returns the maximum/minimum element of the given collection, 
    //according to the natural ordering of its elements.
    //See Employee.compareTo method
    System.out.println("Max salaried employee is " + Collections.max(empList));
    System.out.println("Min salaried employee is " + Collections.min(empList));

  }
}

class Employee implements Comparable<Employee> {
  private String name;
  private int salary;
  
  public Employee(String name, int salary) {
    super();
    this.name = name;
    this.salary = 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;
  }

  @Override
  public int compareTo(Employee other) {
    return new Integer(salary).compareTo(new Integer(other.salary));
  }
  
  public String toString() {
    return "[" + name + ", " + salary + "]";
  }

}
   

It gives the following output,
Max salaried employee is [NINE, 820000]
Min salaried employee is [THREE, 120000]



 
  


  
bl  br