如何转换HashMap <string,arraylist <myclass =“”>&gt;到java中的ArrayList <myclass>?</myclass> </string,>

时间:2012-12-24 13:25:18

标签: java

我用Google搜索,但没有将HashMap<String, ArrayList<Class>>转换为ArrayList<Class>。有人可以帮帮我吗?

基本上,我想从调用构造函数更改下面的方法getStudentLst,并将哈希映射转换为arrayList,如下所示。我已经尝试了很多次,但它一直产生错误。我哪里出错了?

  ArrayList<Student> arrStudLst = new ArrayList<Student>(hmpStudent.keySet());
  Collectoins.sort(arrStudLst, new Comparator());
  return arrStudLst;

但它不起作用并生成错误“构造函数ArrayList(Set)未定义

任何帮助非常感谢!亚当

/* works well but i want to avoid calling constructor */
public ArrayList<Student> getStudentLst(HashMap<String, ArrayList<Student>> hmpStudent)
{
     ArrayList<Student> arrStudLst = new ArrayList<Student>();   
     Set<String> keylst = hmpStudent.keySet();
     Student student;
     for(String keys: keylst)
     {         
        for(Student f: hmpStudent.get(keys))
        {       
         student = new Student(f.getName(),f.getGrade(), f.getTeacher());                arrStudLst.add(student);
        }
     }
     Collections.sort(arrStudLst,new StudentComparator());
     return arrStudLst;
}

4 个答案:

答案 0 :(得分:1)

您尝试使用地图的键初始化列表。但关键是字符串,他们不是学生。

您需要在地图的每个值中返回包含每个学生的列表。所以代码是:

Set<Student> allStudents = new HashSet<Student>(); // use a set to avoid duplicate students
for (List<Student> list : map.values()) {
    allStudents.addAll(list);
}
List<Student> allStudentsAsList = new ArrayList<Student>(allStudents);

答案 1 :(得分:0)

我可以尝试

ArrayList<MyClass> list = new ArrayList<>();
for (ArrayList<MyClass> l : map.values()) {
    list.addAll(l);
}

答案 2 :(得分:0)

键是String,所以 hmpStudent.keySet()将返回List<String>而不是List<Student>

 new ArrayList<Student>(hmpStudent.keySet());

因此上述陈述将失败。您可以使用下面提到的方法

public List<Student> getAllStudents(Map<String, ArrayList<Student> map){
   List<Student> allStudents = new ArrayList<Student>();
   for (List<Student> list : map.values()) {
       allStudents.addAll(list);
   }
   return allStudents;
}

答案 3 :(得分:0)

如果地图中的ArrayList很大但地图中的元素较少,那么您可以尝试这样做。

public ArrayList<Student> getStudentLst(HashMap<String, ArrayList<Student>> hmpStudent)
{
   List<Student> arrStudLst = new ArrayList<Student>();
   for(ArrayList<Student> studentLst : hmpStudent.values()) {
       arrStudLst.addAll(studentLst);
   }
     Collections.sort(arrStudLst,new StudentComparator());
     return arrStudLst;
}