Java Comparator Example

Java Comparator Example

Can you provide me an example of Comparator Interface?

View Answers

June 22, 2012 at 12:35 PM

A comparator object is capable of comparing two different objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).

Here is an example that compares the object of class Person by age.

import java.util.*;

class Person{
    int age;    
    String name;

    public void setAge(int age){
        this.age=age;    
    }
    public int getAge(){
        return this.age;    
    }
    public void setName(String name){
        this.name=name;    
    }
    public String getName(){    
        return this.name;    
    }
}
 class AgeComparator implements Comparator{

    public int compare(Object ob1, Object ob2){
        int ob1Age = ((Person)ob1).getAge();        
        int ob2Age = ((Person)ob2).getAge();

        if(ob1Age > ob2Age)
            return 1;
        else if(ob1Age < ob2Age)
            return -1;
        else
            return 0;    
    }
 }
 public class ComparatorExample{
       public static void main(String args[]){
        Person person[] = new Person[3];

        person[0] = new Person();
        person[0].setAge(35);
        person[0].setName("A");

        person[1] = new Person();
        person[1].setAge(30);
        person[1].setName("B");

        person[2] = new Person();
        person[2].setAge(32);
        person[2].setName("C");

        System.out.println("Order of person before sorting is");
        for(int i=0; i < person.length; i++){
            System.out.println( person[i].getName() + "\t" + person[i].getAge());
        }

        Arrays.sort(person, new AgeComparator());
        System.out.println("\n\nOrder of person after sorting by person age is");

        for(int i=0; i < person.length; i++){
            System.out.println( person[i].getName() + "\t" + person[i].getAge());
        }
       }
    }

August 31, 2012 at 12:52 PM

public class Employee{

int empId;
String eName;

public Employee(int empId, String eName) {

    this.empId = empId;
    this.eName = eName;
}


@Override
public String toString() {

    return "ID:"+empId+"NAME:"+eName;   
}

}


public class Student { String sName; String sDept;

public Student(String sName, String sDept) { this.sName = sName; this.sDept = sDept; }

@Override public String toString() {

return "NAME:"+sName+"DEPT:"+sDept;

}

}


import java.util.Comparator;

public class CommonSort implements Comparator{

@Override
public int compare(Object obj1, Object obj2) {

    int i=0;

    if((obj1!=null && obj2!=null) && obj1 instanceof Employee && obj2 instanceof Employee){

        Employee e1=(Employee)obj1;
        Employee e2=(Employee)obj2;
        i=e1.eName.compareTo(e2.eName);
        System.out.println(e1.eName+"--"+e2.eName+"--"+i);

    }

    if((obj1!=null && obj2!=null) && obj1 instanceof Student && obj2 instanceof Student){

        Student s1=(Student)obj1;
        Student s2=(Student)obj2;
        i=s1.sDept.compareTo(s2.sDept);


    }
    return i;
}

}

import java.util.Iterator; import java.util.TreeSet;

public class EmpMain {

/**
 * @param args
 */
public static void main(String[] args) {

    CommonSort cs=new CommonSort();

    TreeSet<Employee> ts =new TreeSet<Employee>(cs);
    ts.add(new Employee(123,"vijay"));
    ts.add(new Employee(98,"kumar"));
    ts.add(new Employee(100,"abhi"));
    ts.add(new Employee(50,"dhruv"));
    ts.add(new Employee(150,"sasi"));

    for (Iterator iterator = ts.iterator(); iterator.hasNext();) {
        Employee employee = (Employee) iterator.next();
        System.out.println(employee);
    }

    System.out.println("-----------------------------------");

    TreeSet<Student> ts2 =new TreeSet<Student>(cs);
    ts2.add(new Student("kumar","cse"));
    ts2.add(new Student("abhi","it"));
    ts2.add(new Student("vijay","mec"));
    ts2.add(new Student("bhavani","ece"));
    ts2.add(new Student("sasi","eee"));

    for (Iterator iterator = ts2.iterator(); iterator.hasNext();) {
        Student student = (Student) iterator.next();
        System.out.println(student);
    }

}

}


August 31, 2012 at 12:54 PM

the above example is for the statement:

Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).


August 31, 2012 at 12:55 PM

output:

kumar--vijay---11
abhi--vijay---21
abhi--kumar---10
dhruv--kumar---7
dhruv--abhi--3
sasi--kumar--8
sasi--vijay---3

ID:100NAME:abhi
ID:50NAME:dhruv
ID:98NAME:kumar
ID:150NAME:sasi
ID:123NAME:vijay

NAME:kumarDEPT:cse
NAME:bhavaniDEPT:ece
NAME:sasiDEPT:eee
NAME:abhiDEPT:it
NAME:vijayDEPT:mec









Related Tutorials/Questions & Answers:
Java Comparator Example
Java Comparator Example  Can you provide me an example of Comparator Interface?   A comparator object is capable of comparing two different... is an example that compares the object of class Person by age. import java.util.
comparator
comparator  what is a comparator   Hi Friend, A comparator is an interface that can be used to create objects to pass to sort methods or sorting data structures. A Comparator must define a compare function which takes
Advertisements
ModuleNotFoundError: No module named 'comparator'
ModuleNotFoundError: No module named 'comparator'  Hi, My Python... 'comparator' How to remove the ModuleNotFoundError: No module named 'comparator' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'comparator'
ModuleNotFoundError: No module named 'comparator'  Hi, My Python... 'comparator' How to remove the ModuleNotFoundError: No module named 'comparator' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'names_comparator'
ModuleNotFoundError: No module named 'names_comparator'  Hi, My... named 'names_comparator' How to remove the ModuleNotFoundError: No module named 'names_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'version-comparator'
ModuleNotFoundError: No module named 'version-comparator'  Hi, My... named 'version-comparator' How to remove the ModuleNotFoundError: No module named 'version-comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'bibtex_comparator'
ModuleNotFoundError: No module named 'bibtex_comparator'  Hi, My... named 'bibtex_comparator' How to remove the ModuleNotFoundError: No module named 'bibtex_comparator' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'json-dict-comparator'
ModuleNotFoundError: No module named 'json-dict-comparator'  Hi...: No module named 'json-dict-comparator' How to remove the ModuleNotFoundError: No module named 'json-dict-comparator' error? Thanks   Hi
PDF Comparator
java persistence example
java persistence example  java persistence example
Java Client Application example
Java Client Application example  Java Client Application example
Example of HashSet class in java
Example of HashSet class in java. In this part of tutorial, we... unique. You can not store duplicate value. Java hashset example. How.... Example of Hashset iterator method in java. Example of Hashset size() method
What is array in java with example?
What is array in java with example?  Hi, I am beginner in Java and want to learn Java Array concepts. Which is the best tutorials for learn Java Array with example codes? What is array in java with example? Thanks
Java FTP Client Example
Java FTP Client Example  How to write Java FTP Client Example code? Thanks   Hi, Here is the example code of simple FTP client in Java which downloads image from server FTP Download file example. Thanks
Example of HashMap class in java
Example of HashMap class in java. The HashMap is a class in java collection framwork. It stores values in the form of key/value pair. It is not synchronized
Java Collection : TreeSet Example
Java Collection : TreeSet Example This tutorial contains description of  TreeSet with example. TreeSet  : TreeSet class is defined in java.util... or by the comparator. Since it provides fast access and fast retrieval so
FTP Java example
FTP Java example  Where is the FTP Java example on your website? I am... examples of FTP at: FTP Programming in Java tutorials with example code. Thaks... functionality in my Java based application. My application is swing based and I have
freemarker example - Java Beginners
an example for freemarker. i want to get the values from java and display those values in the page designed using freemarker(how to get the values from java). and please provide an example with code and directory structure. send me ASAP
Example Code - Java Beginners
Example Code  I want simple Scanner Class Example in Java and WrapperClass Example. What is the Purpose of Wrapper Class and Scanner Class . when i compile the Scanner Class Example the error occur : Can not Resolve symbol
Java FTP Example
Java FTP Example  Is there any java ftp example and tutorials... and tutorials that teaches you how to user FTP in your Java project. Most commonly used FTP api in java is Apache FTP. Browse all the FTP tutorials at Java FTP
Need an Example of calendar event in java
Need an Example of calendar event in java  can somebody give me an example of calendar event of java
java string comparison example
java string comparison example  how to use equals method in String... strings are not same. Description:-Here is an example of comparing two strings using equals() method. In the above example, we have declared two string
Java nested class example
Java nested class example  Give me any example of Nested Class.   Nested Class: Class defined within another class is called nested class... class. Example: public class NestedClass{ private String outer = "Outer
throws example program java
throws example program java  how to use throws exception in java?   The throws keyword is used to indicate that the method raises..." java.lang.ArithmeticException: / by zero Description:- Here is an example of throws clause. We
what is the example of wifi in java
what is the example of wifi in java  i want wi fi programs codings
example
example  example on Struts framework
example
example  example on Struts framework
Java Comparable Example
Java Comparable Example  I want to know the use of Comparable Interface. Please provide me one example   Comparable interface is used.... Here is an example that compares two ages using Comparable Interface. import
Java hashset example.
Java hashset example.     HashSet is a collection. You can not store duplicate value in HashSet. In this java hashset exmple, you will see how to create HashSet in java application and how to store value in Hashset
Java collection Stack example
:- -1 Description:- The above example demonstrates you the Stack class in java...Java collection Stack example  How to use Stack class in java.... Here is an example of Stack class. import java.util.Stack; public class
Inheritance java Example
Inheritance java Example  How can we use inheritance in java program... for bread Description:- The above example demonstrates you the concept... properties of the superclass. In the given example, the class Animal is a superclass
Java HashMap example.
Java HashMap example. The HashMap is a class in java. It stores values in name values pair. You can store null value of key and values.   Here... of map. Code:  HashMapExample .java (adsbygoogle
Java Map Example
Java Map Example  How we can use Map in java collection?   The Map interface maps unique keys to value means it associate value to unique... Description:- The above example demonstrates you the Map interface. Since Map
example explanation - Java Beginners
example explanation  can i have some explanation regarding the program given as serialization xample....  Hi friend, import java.io..../java
Java File Management Example
of file. Read the example Read file in Java for more information on reading...Java File Management Example  Hi, Is there any ready made API in Java for creating and updating data into text file? How a programmer can write code
java program example - Java Beginners
java program example  can we create java program without static and main?can u plzz explain with an example
java binary file io example
java binary file io example  java binary file io example
Core java linked list example
Core java linked list example  What is the real time example for linked list
array example - Java Beginners
i cannot solve this example
example
example  i need ex on struts-hibernate-spring intergration example   Struts Spring Hibernate Integration
Static Method in java with realtime Example
Static Method in java with realtime Example  could you please make me clear with Static Method in java with real-time Example
printing example - Java Beginners
printing example  Is it possible to print java controls using print method? My problem is to print a student mark list using java? The mark list should like that of university mark list
pattern java example
pattern java example  how to print this 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15

Ads