Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting Vector on Multiple Keys

Status
Not open for further replies.

jsulman

Programmer
Jun 14, 2001
85
US
I am trying to sort a vector with mulitple keys. I can do it with one key by using a Comparator with the following code:

class CompTypeComparator implements Comparator {
public int compare(Object o1, Object o2) {
int j1 = ((CompType)o1).j;
int j2 = ((CompType)o2).j;
return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
}
}

I can even do it on two keys with the following code using the CompareTon where Name is a vector containing a first and last name.

public int compareTo(Object o)
{
Name n = (Name)o;
int lastCmp = lastName.compareTo(n.lastName);
System.out.println(lastName + &quot;/&quot; + n.lastName + &quot;/&quot; + lastCmp);
return (lastCmp!=0 ? lastCmp : firstName.compareTo(n.firstName));
}

How would I use one of these models, or any other, to sort 3 or more strings (keys) i.e. first, mi, and last name?

Thanks in advance.

Jeff Sulman
 
If it are all strings can't you just concatenate the strings in your compare method and do the compare with the concatenated strings. [You probably have to put a space or another seperator character between the strings]. This sounds too easy to be true.
 
Hologram,
I was going to consider your solution but it would not allow for the ability to make each of the rows ascending or descending and they are not all strings - which is going to be a problem in and of itself.

Thank

Jeff
 
You can do it in the following way,but implementing could be cumbersome :
You just use your normal sort on the first column of your Vertor.
For the sort on the second column, you have to code a loop that goes over your Vector, and if it finds equals in the sorted columns (the first column), then create a subVector containing only the records where the already sorted field is equal. Then you sort this new Vector on the second column.
=============================
If would be faster if you could create the second (set of Vectors then) while sorting on the first column.
Store your data in a Vector of Vectors of Vectors...?
Or Arrays of arrays... and pass the from and to index to your sort...
=============================
You can repeat this for the other columns.
I think a variation of this appraoch is the best way to go.
======================================================

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top