I have to merge two hashmaps, one results (contains grades), the other
students(contains students, with exam results. Their exam marks are
averaged out and graded. I need the students to appear in the results
hashmap against their grade, can somebody please point out what is
wrong with the following:
public void collateResults()
{
char grades[] = {'A', 'B', 'C', 'D', 'F', 'X'};
{
for (Character grade : grades)
{
this.results.put(grade, new HashSet<String>());
}
for (String eachStudent : students.keySet())
{
for(String graded : this.results.get(eachStudent))
{
this.results.get(graded).add(eachStudent);
}
}
}
}
Any help greatly appreciated.
Paul
Tom Hawtin - 12 Mar 2007 20:37 GMT
> for (Character grade : grades)
> {
> this.results.put(grade, new HashSet<String>());
So the key to results is a Character.
> }
> for (String eachStudent : students.keySet())
> {
> for(String graded : this.results.get(eachStudent))
> {
> this.results.get(graded).add(eachStudent);
And here you are using Strings as the key.
An object cannot be simultaneously a Character and a String, so they
will never match.
(As I said earlier, the code would be much clearer if 'grade' was an
abstract type.)
Tom Hawtin
Mark Rafn - 12 Mar 2007 20:56 GMT
>I have to merge two hashmaps, one results (contains grades), the other
>students(contains students, with exam results.
Smells like homework. You may get some hints, but you should ask more
specific questions and describe what you've tried and what specific part you
don't understand.
Maps contain keys and values. You haven't described which is which for these
maps.
>Their exam marks are averaged out and graded. I need the students to appear
>in the results hashmap against their grade
I'd call this a join (using data in one map to reference another) rather than
a merge (take two similar hashmaps and combine them).
>public void collateResults()
> {
[quoted text clipped - 13 lines]
> }
>}
1) a "results" member variable is usually a sign of broken class design. If
the class represents something, name the variable better. If this is a method
that should calculate and return, but not keep the results, then maybe
public Map<Char, Set<String>> getStudentsByGrade(Map<String, Char> students)
is a better signature.
2) you're trying to access the "results" map in two different ways. In one
spot it looks like it's keyed by grade, in another by student.
--
Mark Rafn dagon@dagon.net <http://www.dagon.net/>
Gagan - 13 Mar 2007 17:27 GMT
Here is what you could do:
1. Preparae various lists of like graded students (you may itrerate
the existing students set and group like graded students in various
lists). Am assuming student does contain grade variable inside it.
2. Have a hashmap (grade as key and list as value), the list is
reference to the list of correponding like graded students list.
Gagan