Originally posted by rathi ji:
Good question.![]()
I don't know any particular method from API. But you can do it programatically, map has values() method, get collection of values from this method then call sort() method of Collections utility class (override compareTo() method of comparable interface if it require...) then again store data back to map.
I hope everything is right and clear.
Originally posted by Layne Lund:
My first instinct is to ask "Why do you want to do this?" I wonder if there is a better way to accomplish what you want to do. If you would like to describe the overall problem in some more detail, we will be more than willing to offer alternate solutions. One possibility is to create your own class that contains the data that you are currently using as the value and key in your Map. Either this class can implement Comparable or you can write a separate class that implements Comparator. Then you can create a List with objects of this custom class and use Collections.sort() to sort it. Without knowing the exact details of your project, I cannot tell if this is a good way to solve the problem, though. This is just an example to show that there are alternative approaches.
With that said, you can sort a Map by its values in several ways. One way uses the entrySet() method and a new Map (or maybe a List). I'll leave the details as the proverbial exercise for the reader.
Layne
A data structure with students and their marks is given, you have to calculate the percentile of the students aaccording to this rule: the percentile of a student is the % of no of student having marks less
then him. For eg:
suppose
Student Marks
A 12
B 60
C 80
D 71
E 30
F 45
percentile of C = 5/5 *100 = 100 (out of 5 students 5
are having marks less then him)
percentile of B = 3/5*100 = 60% (out of 5, 3 have
markses less then him)
percentile of A = 0/5*100 = 0%.
Originally posted by Ernest Friedman-Hill:
The "Java Way" to do this:
1) Create a Mark class, which stores a student name and grade in member variables
2) Write another class GradeComparator that implements Comparator, and compares two Mark objects based on grades
3) From the daata, create a bunch of Mark objects, and put them in a List
4) Sort the List using the GradeComparator.
There's no Map involved.
Originally posted by Layne Lund:
To me, this means that implementing Comparable would be more natural than creating a separate Comparator.
Originally posted by Ernest Friedman-Hill:
Unless you next want to print out a chart of students and their grades to hang on your office door! It could go either way, really. I tend to use Comparable fairly rarely in my own work, on the assumption that there are always multiple ways to sort things...
Consider Paul's rocket mass heater. |