I have two arrays; one is defined as integer and the other is String. I want to sort the int array in descending order but still maintain the occurence relationship between the two tables. For example, given:
occurence arr1 arr2 1 8 cat 2 10 dog 3 2 fish 4 7 horse
I would like to produce:
occurence arr1 arr2 1 10 dog 2 8 cat 3 7 horse 4 2 fish
I could use a prewritten java sort method for arr1 but I'm not sure how to preserve the occurence relationship between the content in both arrays. Any suggestions would be greatly appreciated.
There's probably an easier way, but this is how I would do it.
Presuming there is a one-to-one correspondence between the Integer and the String, you can store the data in a HashMap<Integer,String>. This establishes a key,value association between the two items. After that, you can sort the HashMap.keySet and use the sorted set to retrieve the String values from the HashMap in the desired order.
P.S. Or you can just make things easy on yourself and take Peter's excellent suggestion. [ October 23, 2007: Message edited by: Bridget Kennedy ]
posted 11 years ago
I really appreciate the feedback. I'll give your suggestions a try and let you know how it goes - Sebastian
Note that most of the time when you find yourself with "parallel arrays" like this, wanting to sort them together and all, that's a very strong hint that there's a little class waiting to be born -- in this case, a Bean-like class with a String and an int as members, that implements Comparable.
I loaded both a hashmap and a treemap with my array values. I can iterate through and print the occurences in ascending order but I'm still struggling with presenting them in descending order which is what I need.
I found a method called "descendingMap()" java 1.6.0 in the TreeMap class that seems to fit the bill but I can't get this to compile clean.
Map sortedMap = new TreeMap(m); /*moved my array data to a hashmap "m"then created a TreeMap as a test. Final code will directly populate the TreeMap */
sortedMap.descendingMap(); /* does not recognize this method but it is listed in the java API 1.6.0 doc*/
System.out.println("Retriving all values from the TreeMap");