我試圖從Student
對象的ArrayList
創建一個HashMap
。我想從名稱中選取字母作爲鍵,並根據名稱將每個數組列表附加到該鍵上。使用唯一鍵和值創建一個HashMap asArrayList
例如,如果輸入是:
Student{roll no.,Name, Age} {105,Alex,23} {102,Alexander,24} {101,Becky,23}
的HashMap
應該是:
{A,{105,Alex,23}}{102,Alexander,24}}{B,{101,Becky,23}}.
我的代碼:
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); } }
*/
}
}
輸出:
Sorting ArrayList by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
HashMap.....
V [[email protected], [email protected], [email protected]]
A [[email protected], [email protected], [email protected]]
J [[email protected], [email protected], [email protected]]
向'Student'類添加'toString'方法以避免像'moduletest.Student @ 1f5b44d6'這樣的輸出。你可以使用'MultiMap'(http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html)。 – Tom 2014-10-07 18:40:08