I am trying to create a HashMap from an ArrayList of Student objects. I want to pick up alphabets from the name as keys and attach each array list to that key based on the name.
For example, if the input is:
Student{roll no.,Name, Age} {105,Alex,23} {102,Alexander,24} {101,Becky,23}
The HashMap should be:
{A,{105,Alex,23}}{102,Alexander,24}}{B,{101,Becky,23}}.
My code:
package moduletest;
import java.util.*;
import java.io.*;
class Simple {
@SuppressWarnings("unchecked")
public static void main(String args[]) {
ArrayList al = new ArrayList();
HashMap<Character, ArrayList<Student>> hm = new HashMap<Character, ArrayList<Student>>();
al.add(new Student(101, "Vijay", 23));
al.add(new Student(106, "Ajay", 27));
al.add(new Student(105, "Jai", 21));
System.out.println("Sorting ArrayList by Name...");
Collections.sort(al, new NameComparator());
Iterator itr = al.iterator();
while (itr.hasNext()) {
Student st = (Student) itr.next();
Character key = st.name.charAt(0);
hm.put(key, al);
System.out.println(st.rollno + " " + st.name + " " + st.age);
}
System.out.println("HashMap.....");
for (Map.Entry m : hm.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
/*
* Character[] keys = new Character[hm.size()]; Object[] values = new
* Object[hm.size()]; int index = 0; for (Map.Entry<Character,
* ArrayList<Student>> mapEntry : hm.entrySet()) { keys[index] =
* mapEntry.getKey(); values[index] = mapEntry.getValue(); index++; }
* for(Character chr:keys) { System.out.println(chr); } for(Object
* value:values) { Iterator itr1 = ((ArrayList) value).iterator(); while
* (itr1.hasNext()) { Student st1 = (Student) itr1.next();
* System.out.println(st1.rollno + " " + st1.name + " " + st1.age); } }
*/
}
}
Output:
Sorting ArrayList by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
HashMap.....
V [moduletest.Student@1f5b44d6, moduletest.Student@21044daf, moduletest.Student@21882d18]
A [moduletest.Student@1f5b44d6, moduletest.Student@21044daf, moduletest.Student@21882d18]
J [moduletest.Student@1f5b44d6, moduletest.Student@21044daf, moduletest.Student@21882d18]
toStringmethod to youStudentclass to avoid output likemoduletest.Student@1f5b44d6. And you may use aMultiMap(docs.guava-libraries.googlecode.com/git/javadoc/com/google/…).