我正在尝试从HashMap
个ArrayList
个对象创建Student
。我想从名称中选取字母作为键,并根据名称将每个数组列表附加到该键。
例如,如果输入为:
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 [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]
答案 0 :(得分:4)
那是错的:
Character key = st.name.charAt(0);
hm.put(key, al);
您将整个ArrayList作为每个键的值。
您应该为每个键创建一个新的ArrayList,并且只将名称以相同字符开头的学生放入其中。
Character key = st.name.charAt(0);
List l = null;
if (hm.containsKey(key))
l = hm.get(key);
else {
l = new ArrayList<Student>();
hm.put(key, l);
}
l.add(st);
答案 1 :(得分:1)
不是超级高效,但尝试这样的事情......
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(101, "Vijay", 23));
al.add(new Student(106, "Ajay", 27));
al.add(new Student(105, "Jai", 21));
Map<Character, ArrayList<Student>> hm = new TreeMap<String, ArrayList<Student>>();
for (Student student : al) {
Character key = student.name.charAt(0);
ArrayList<Student> list = hm.get(key); // get the existing list
if (list == null) {
list = new ArrayList<Student>();
}
list.add(student); // add this student to it
hm.put(key, list); // replace it in the map, under the correct key
}
TreeMap将保持排序顺序。