0

I have a HashMap which holds studentIds as key and student objects as values,

HashMap<Integer, Student> hashMap = hashTables.buildHash(students);

public static HashMap<Integer, Student> buildHash(Student[] students) {
            HashMap<Integer, Student> hashMap = new HashMap<Integer, Student>();
            for (Student s : students) hashMap.put(s.getId(), s);
            return hashMap;
       }

the below code gets each KeyValue pair and s.getValue() returns a student object which is comprised of an id and an string name, how can i retrieve/print those values (student.int, student.name);

for(Map.Entry s : hashMap.entrySet())
    System.out.print(s.getKey()+" "+s.getValue());

3 Answers 3

3

Just implement toString in Student and the code you posted will work as-is:

public class Student {
    ...
    public String toString() {
      return "ID = " + this.id + ", name = " + this.name;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there anyway that i could retrieve the int and string values of the object?
See Michael Borgwardt's answer on that, he has it covered. The point is to use type parameters on the Map.Entry's declaration. Then you can freely write e.getValue().getId().
3

You just have to use the parameterized type for the entry:

for(Map.Entry<Integer, Student> s : hashMap.entrySet())
    System.out.print(s.getKey()+" "+s.getValue().getId()+" "+s.getValue().getName());

(note that it's impossible for a class to have a field named "int" because that's a language keyword).

2 Comments

@Marko Topolnik: only because I was using the OP's syntax-violating infor about his class' structure
Of course, I realized the humoristic aspect of it. Just that it's better to help than to mock :) Mind also that in the HashMap population code he uses a getter, so probably his id and name are private, as they should be.
1

You can acheive this by..

for(Map.Entry<Integer, Student> s : hashMap.entrySet()){
    System.out.print(Long.valueof(s.getKey())+""+String.valueof(s.getValue().getName()));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.