This post originated from an RSS feed registered with Java Buzz
by Ram N.
Original Post: Java : Collection Framework : Collections (BinarySearch Comparator)
Feed Title: JAVA EE
Feed URL: http://ramj2ee.blogspot.com/feeds/posts/default?alt=rss
Feed Description: This blog has viedo tutorials and Sample codes related to below Technologies.
1.J2EE
2.Java
3.Spring
4.Hibernate
5.Database
6.Oracle
7.Mysql
8.Design Patterns
public class Employee { private Integer employeeId; private String name;
public Employee( Integer employeeId, String name ) { super(); this.employeeId = employeeId; this.name = name; }
public Integer 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 +"]"; }
}
EmployeeIdComparator.java
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) {
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
Parameters:
list - the list to be searched. key - the key to be searched for. c - the comparator by which the list is ordered. A null value indicates that the elements' natural ordering should be used.
Returns:
the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
System.out .println("employeeList after sort : \n"+ employeeList +"\n");
/* * Searches the specified list for the specified object using the binary * search algorithm. The list must be sorted into ascending order * according to the specified comparator (as by the sort(List, * Comparator) method), prior to making this call. * * If it is not sorted,the results are undefined. If the list contains * multiple elements equal to the specified object, there is no * guarantee which one will be found. */
Employee searchKey =new Employee(202, null);
int index = Collections.binarySearch(employeeList, searchKey, employeeIdComparator);
System.out.println("index : "+ index);
Employee employee = employeeList.get(index); System.out.println("employee name in '"+index+"' index Position : " + employee.getName());