in Java Comparator is a comparison function that enforces the objects of a collection totally in ordered.
Java Collection Framework - Comparator
In general Comparator means a comparison device that making a comparison with similar thing or with some other standard measure. As similar in Java Comparator is a comparison function that enforces the objects of a collection totally in ordered. The collection objects that are not in their natural order, to provide a control on the sort order Comparator can pass by collections.sort or Arrays.sort sorting method and it can also be used for controlling the order of data structures or allowing an order for collection's of object's. The order of objects brought down by a comparator 'cm' on an element's set S = {e1,e2,....} is called consistent with equals iff the boolean value of {cm.compare(e1,e2)= = 0} is similar as the boolean value of { e1.equals(e2) } for all e1 and e2 in S.
Syntax
public interface Comparator<T>
Methods of Comparator
Following are the method of Comparator :
- compare()
syntax : int compare(T o1, T o2)
- equals(Object obj)
syntax : boolean equals(Object obj)
Example :
package devmanuals.com; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ComparatorDemo implements Comparator<ComparatorDemo>, Comparable<ComparatorDemo> { String name; int age; ComparatorDemo() { } ComparatorDemo(String n, int a) { this.name = n; this.age = a; } public String getName() { return name; } public int getAge() { return age; } public int compareTo(ComparatorDemo e) { return (this.name).compareTo(e.name); } public int compare(ComparatorDemo cd, ComparatorDemo cd1) { return cd.age - cd1.age; } public static void main(String[] args) { List<ComparatorDemo> l = new ArrayList<ComparatorDemo>(); System.out.println("list sorted by name in increasing order"); l.add(new ComparatorDemo("Piyush", 5)); l.add(new ComparatorDemo("Tom", 4)); l.add(new ComparatorDemo("Titu", 7)); l.add(new ComparatorDemo("Dom", 9)); l.add(new ComparatorDemo("Bipul", 25)); l.add(new ComparatorDemo("Vinay", 26)); l.add(new ComparatorDemo("Rajesh", 29)); l.add(new ComparatorDemo("Ankit", 27)); Collections.sort(l); System.out.println("\tName \t Age\n"); for (ComparatorDemo c : l) System.out.println("\t" + c.getName() + "\t " + c.getAge()); Collections.sort(l, new ComparatorDemo()); System.out.println(" "); System.out.println("list sorted by age in increasing order"); System.out.println("\tName \t Age\n"); for (ComparatorDemo c1 : l) System.out.println("\t" + c1.getName() + "\t " + c1.getAge()); } }
Output :
list sorted by name in increasing order Name Age Ankit 27 Bipul 25 Dom 9 Piyush 5 Rajesh 29 Titu 7 Tom 4 Vinay 26
list sorted by age in increasing order Name Age Tom 4 Piyush 5 Titu 7 Dom 9 Bipul 25 Vinay 26 Ankit 27 Rajesh 29 |
[ 0 ] Comments