Comparator?

K

Knute Johnson

I've got a question about how to create a Comparator that I can use to
keep a sorted list of objects. The sort fields would be a code that is
not something to be sorted directly and a String that I would want
alphabetical. I would have a list of the codes and that list would be
in the sorted order. What I want to do is put the data in order
according to the list of codes and the other String.

The codes are actually going to be a 3 letter String. For example the
codes could be;

XAB
AJC
BQP
RST

and the data would be a code String and another String to sort
alphabetically.

XAB San Francisco
BQP Alabama
XAB Houston
AJC Montreal

I want the data sorted in this order:

XAB Houston
XAB San Francisco
AJC Montreal
BQP Alabama

Any simple ideas on how to design the Comparator?

Thanks,
 
R

Roedy Green

I've got a question about how to create a Comparator that I can use to
keep a sorted list of objects

see http://mindprod.com/applet/comparatorcutter.html

Just fill in the blanks and it will generate you the Java code you
need.

You could do thing with strings with the airport code in the first
three slots or with objects with an airport and City name String
field.
--
Roedy Green Canadian Mind Products
http://mindprod.com
For me, the appeal of computer programming is that
even though I am quite a klutz,
I can still produce something, in a sense
perfect, because the computer gives me as many
chances as I please to get it right.
 
K

Knute Johnson

I would deal with the codes by creating a Map<String,Integer>, and
initializing it to map each code to its index in the original list.

In the compare method, first compare the results of looking up the codes
in the map. If that gives equality, then compare the city name strings
to resolve the comparison.

Patricia

Thanks very much Patricia.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top