user1362208
user1362208

Reputation:

Retrieving objects from HashMap in Java?

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());

Upvotes: 0

Views: 4944

Answers (3)

PVR
PVR

Reputation: 2524

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()));
}

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

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).

Upvotes: 3

Marko Topolnik
Marko Topolnik

Reputation: 200138

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;
    }
}

Upvotes: 3

Related Questions