Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Sorting HashMap

807580Oct 4 2009 — edited Oct 5 2009
Hi all,

I have a hashmap with containing a string and a double value with about 20 records.
hashMap.put(CarID, CarResult);
Next I want to sort the hashmap according to the CarResult. My codes are as such:
List<Integer> mapKeys = new ArrayList<Integer>(hashMap.keySet());
        List<Double> mapValues = new ArrayList<Double>(hashMap.values());

        HashMap<Integer, Double> sortedMap = new LinkedHashMap<Integer, Double>();

       TreeSet<Double> sortedSet = new TreeSet<Double>(mapValues);
       Object[] sortedArray = sortedSet.toArray();

for (int q = size; q > 0;) {
            sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[--q])),
                    (Double) sortedArray[q]);

            System.out.println(mapKeys.get(mapValues.indexOf(sortedArray[q])) + " " + (Double) sortedArray[q]);
        }
The final results that I expected was to have the hashmap sorted according to the CarResult in descending order, displaying 20 records.The values in hashmap contains duplicated data.

001 1.433333
002 1.0
003 0.2
004 0.2
etc all the way to the 20th records

However, when i run the codes, all the duplicated copies were being deleted. Instead of 20 records, I got about 12 copies of result.

Qns: How do I work around the problem of preventing duplicated copies from being deleted? If this is not possible, are there any ways to sort a hashmap without having the duplicated copies deleted??

Thanks in advance
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 2 2009
Added on Oct 4 2009
8 comments
142 views