+ 4
Java Collections - Map and List
In Map how do we pass a class as value. For eg- I have a Student class with two fields as name and department. Let us say I put a integer type key. Map<Integer, List<Student>> map = new HashMap<>(); The above does not give me any error but while inserting the values it shows some error, may be I'm doing it wrong. map.put(1, new Student("name", "dept")); What is the right way to insert values inside the map?
8 Answers
+ 9
Avinesh Check this code.
https://code.sololearn.com/csCtb155654V/?ref=app
+ 8
It means you want to put list of Student in map as a value.
Map<Integer,List<Student>> map = new HashMap<>();
For adding a value in map
List<Student> list = new ArrayList<>();
map.put(0,list);
If you want to put the student as value and not the list of student then
Map<Integer,Student> map = new HashMap<>();
map.put(1,new Student());
+ 5
Avinesh You have declared a map with the value of list so you cannot directly put a class
To achieve this you need to create a list first then you can put in map like this:-
Map<Integer, List<Student>> map = new HashMap<>();
List<Student> stlist = new ArrayList<>();
Student s = new Student();
slist.add(s);
map.put(1, slist);
+ 5
I shouldn't have included List, just Student would have done the job.
I was trying to map a student to an integer value so the List was not necessary.
But adding a List would be like mapping many students to a single integer value.
Thanks a lot guys
Ravi Prakash
Sumit Programmerđđ
And specially đ
°đ
š - ÉŞ'á´ á´ĘÉŞá´ÉŞÉ´á´ĘĘĘ É˘á´á´á´
! for the code you made for this.
+ 4
Avinesh You can use Map in different ways according to your requirements. Here are some examples:-
Map<Long, Student> map;
Map<Long, List<Student>> map;
Map<Long, Map<Long, Student>> map;
Map<Long, Map<Long, List<Student>>> map;
+ 4
đ
°đ
š - ÉŞ'á´ á´ĘÉŞá´ÉŞÉ´á´ĘĘĘ É˘á´á´á´
! Those are some really nice examples, will try those for sure.
Just started digging collections so probably I might come up with more questions.
+ 2
Map<Integer, Student> map=new HashMap<>();
Try this i think it will work....