Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting an array based on another array

 
Juzer Ali
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm with fred, the existence of parallel arrays almost screams, "Please refactor me into an object!"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic