Click here to watch in Youtube :
https://www.youtube.com/watch?v=z3thHOGJSLQ&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Java : Collection Framework : Collections (Max Comparator) |
Java : Collection Framework : Collections (Max Comparator) |
Employee.java
public class Employee
{ private int employeeId; private String name; public Employee( int employeeId, String name ) { super(); this.employeeId = employeeId; this.name = name; } public int getEmployeeId() { return employeeId; } public void setEmployeeId( int employeeId ) { this.employeeId = employeeId; } public String getName() { return name; } public void setName( String name ) { this.name = name; } @Override public String toString() { return "Employee [employeeId=" + employeeId + ", name=" + name + "]"; } }
import java.util.Comparator; public class EmployeeIdComparator implements Comparator<Employee> { /* * This method used to order the employee objects in Ascending based on employeeId. */ @Override public int compare(Employee employee1, Employee employee2) { if (employee1.getEmployeeId() < employee2.getEmployeeId()) { return -1; } else { return 1; } } }
import java.util.ArrayList; import java.util.Collections; /* Method: public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) Parameters: coll - the collection whose maximum element is to be determined. comp - the comparator with which to determine the maximum element. A null value indicates that the elements' natural ordering should be used. Returns: the maximum element of the given collection, according to the specified comparator. */ public class CollectionsExample { public static void main(String[] args) { ArrayList<Employee> employeeList = new ArrayList<Employee>(); Employee john = new Employee(3, "John"); Employee david = new Employee(2, "David"); Employee peter = new Employee(1, "Peter"); Employee juli = new Employee(5, "Juli"); Employee ram = new Employee(4, "Ram"); employeeList.add(john); employeeList.add(david); employeeList.add(peter); employeeList.add(juli); employeeList.add(ram); System.out.println("employeeList : " + employeeList + "\n"); EmployeeIdComparator employeeIdComparator = new EmployeeIdComparator(); /* * Returns the maximum element of the given collection, according to the * order induced by the specified comparator. */ Employee employee = Collections.max(employeeList, employeeIdComparator); System.out.println("employee object whose employee id is max : " + employee); } }
employeeList : [Employee [employeeId=3, name=John], Employee [employeeId=2, name=David], Employee [employeeId=1, name=Peter], Employee [employeeId=5, name=Juli], Employee [employeeId=4, name=Ram]] employee object whose employee id is max : Employee [employeeId=5, name=Juli]
https://sites.google.com/site/javaee4321/java-collections/CollectionsDemo-MaxComparator.zip?attredirects=0&d=1
See also:
No comments:
Post a Comment