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.
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]