aspose file tools*
The moose likes Beginning Java and the fly likes Sorting an array based on another array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting an array based on another array" Watch "Sorting an array based on another array" New topic
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: 10916
    
  12

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
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: 1296
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting an array based on another array
 
Similar Threads
beginner
getParameterNames curious behaviour
need help using StringTokenizer
concurrency error
Merge sort failure