| Author |
Sorting an array based on another array
|
Juzer Ali
Greenhorn
Joined: Apr 17, 2009
Posts: 2
|
|
Hello All.
I need to sort one array based on the arrangement of another array.
I fetch two arrays from somewhere and they are related.
For example,
Therefore,
Firstly, I need to sort the "name" array alphabetically. I can do that easily using "Arrays.sort(name)" but the problem is that my relationship with the "type" array will be lost. I need to re-order the "name" array alphabetically so that my "type" array also gets sorted automatically depending on the "name" array.
Any help will be much appreciated,
Thanks
Juzer
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9944
|
|
My first thought is that it's bad to have two separate arrays. What happens if you get one sorted, 'something bad happens' and you throw an exception... the second one might easily get out of sync.
What I'd do is either put the 'set' into an object - so you'd have an object that contains both a 'type' and a 'name', put those into an array, and sort the one array.
Another option would be to use a map. Use the 'type' as the key, and the 'name' as the value, then sort your keys. Then you can pull your 'name' out in order by key.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Brian Legg
Ranch Hand
Joined: Nov 07, 2008
Posts: 488
|
|
I would combine the 2 arrays into a Map or HashMap. Set the Map up to automatically sort alphabetically based on the "name" field. Afterwords if you really need 2 seperate arrays just extract them from the Map using Map.values().toArray(). Check out Map if you are unfamiliar. Also check out Comparable and Comparator examples to see how to automatically sort alphabetically.
|
SCJA
~Currently preparing for SCJP6
|
 |
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
|
|
|
I'm with fred, the existence of parallel arrays almost screams, "Please refactor me into an object!"
|
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
|
 |
 |
|
|
subject: Sorting an array based on another array
|
|
|