Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / April 2008

Tip: Looking for answers? Try searching our database.

how to return Comparator values

Thread view: 
Thufir - 26 Apr 2008 23:51 GMT
Just trying to learn how Comparator works.

Looking at:

import java.util.*;
public class EmpSort {
   static final Comparator<Employee> SENIORITY_ORDER =
                                new Comparator<Employee>() {
       public int compare(Employee e1, Employee e2) {
           return e2.hireDate().compareTo(e1.hireDate());
       }
   };

   // Employee database
   static final Collection<Employee> employees = ... ;

   public static void main(String[] args) {
       List<Employee>e = new ArrayList<Employee>(employees);
       Collections.sort(e, SENIORITY_ORDER);
       System.out.println(e);
   }
}

http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

I like the line:

Collections.sort(e, SENIORITY_ORDER); //this will sort the collection
"e" by //SENIORITY_ORDER?

However, how or where is SENIORITY_ORDER ranking defined?  I guess
it's in

return e2.hireDate().compareTo(e1.hireDate());  //neg, zero, pos

which returns either a negative, positive or zero.  We're only
interested in negative results?

I had a specific question, but sorta answered it while writing it...

anyhow.

-Thufir
Matt Humphrey - 27 Apr 2008 00:49 GMT
> Just trying to learn how Comparator works.
>
> Looking at:

<snip code/>

> I like the line:
>
[quoted text clipped - 8 lines]
> which returns either a negative, positive or zero.  We're only
> interested in negative results?

Of course, you should read the Javadocs for the Comparator interface, but in
a nutshell, the compare (a, b) function returns the relative order of the
two items.
If a < b, it should return -1
if a > b it should return +1
if a.equals(b) it should 0

It's up to you to define what "<" means by looking at your own data.  The
compareTo function of Comparables (Strings, Numbers, etc all implement
Comparable) uses the same definition, but you can prioritize the data as you
see fit to determine how you want the order.

Matthew Humphrey http://www.iviz.com/
Lew - 27 Apr 2008 03:27 GMT
"Thufir" wrote ...
>> Just trying to learn how Comparator works.
>>
>> Looking at:
>
> <snip code/>

>>     static final Comparator<Employee> SENIORITY_ORDER =
>>                                  new Comparator<Employee>() {
>>         public int compare(Employee e1, Employee e2) {
>>             return e2.hireDate().compareTo(e1.hireDate());
>>         }
...
>> However, how or where is SENIORITY_ORDER ranking defined?  I guess
>> it's in
[quoted text clipped - 3 lines]
>> which returns either a negative, positive or zero.  We're only
>> interested in negative results?

> Of course, you should read the Javadocs for the Comparator interface, but in

Hear!  Hear!

<http://java.sun.com/javase/6/docs/api/java/util/Comparator.html>

> a nutshell, the compare (a, b) function returns the relative order of the
> two items.
[quoted text clipped - 6 lines]
> Comparable) uses the same definition, but you can prioritize the data as you
> see fit to determine how you want the order.

Example: suppose you have an entity class (simplified):

public class Person
{
 private String name;
 private Double age;
 public void setName( String n ) { name = n; }
 public String getName() { return name; }
 public void setAge( Double a ) { age = a; }
 public Double getAge() { return age; }
}

Sometimes you want to sort by name, sometimes by age, sometimes by first one
then the other.

Here's a sample Comparator for age:

 Comparator <Person> personAgeComparator = new Comparator <Person> ()
  {
    public int compare( Person lef, Person rig )
    {
      if ( lef == null ) { return (rig == null? 0 : -1); }
      if ( rig == null ) { return 1; }
      if ( lef.getAge() == null ) { return (rig.getAge() == null? 0 : -1 }
      if ( rig.getAge() == null ) { return 1; }
      return lef.getAge().compareTo( rig.getAge() );
    }
  }

A more realistic example would use birthdates, which don't change as
continuously as age does.

A name Comparator would be similar, but use a different implementation of the
compare() method, one based on getName() instead of getAge()

One could easily write a Comparator that sorts by age first, then name (or
vice versa).

If a Comparator were to be widely re-used, you'd consider making it a
top-level class:

 class PersonAgeComparator implements Comparator <Person>
 {
    public int compare( Person lef, Person rig )
    {
     // etc.
    }
 }

Signature

Lew

Roedy Green - 27 Apr 2008 03:23 GMT
On Sat, 26 Apr 2008 15:51:20 -0700 (PDT), Thufir
<hawat.thufir@gmail.com> wrote, quoted or indirectly quoted someone
who said :

>Just trying to learn how Comparator works.

see http://mindprod.com/jgloss/comparator.html
and
http://mindprod.com/jgloss/comparable.html
and
http://mindprod.com/jgloss/sort.html

to fill in the blanks.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.