+ 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?

29th Dec 2019, 7:36 AM
Avinesh
Avinesh - avatar
8 Answers
29th Dec 2019, 8:40 AM
A͢J
A͢J - avatar
+ 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());
29th Dec 2019, 8:28 AM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 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);
29th Dec 2019, 8:23 AM
A͢J
A͢J - avatar
+ 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.
29th Dec 2019, 9:23 AM
Avinesh
Avinesh - avatar
+ 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;
29th Dec 2019, 9:28 AM
A͢J
A͢J - avatar
+ 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.
29th Dec 2019, 9:32 AM
Avinesh
Avinesh - avatar
+ 2
Map<Integer, Student> map=new HashMap<>(); Try this i think it will work....
29th Dec 2019, 8:14 AM
Ravi Prakash
Ravi Prakash - avatar