gpt4 book ai didi

java - 如何在java中将HashMap>转换为ArrayList

转载 作者:行者123 更新时间:2023-12-01 14:58:29 24 4
gpt4 key购买 nike

我用谷歌搜索过,但没有遇到转换HashMap<String, ArrayList<Class>>ArrayList<Class> 。有人可以帮我吗?

基本上,我想从调用构造函数更改下面的 getStudentLst 方法,并将 HashMap 转换为 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;
}

最佳答案

您尝试使用 map 的键初始化列表。但 key 是 Strings,他们不是 Students。

您需要返回一个列表,其中包含 map 每个值中的每个学生。所以代码是:

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);

关于java - 如何在java中将HashMap<String, ArrayList<MyClass>>转换为ArrayList<MyClass>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14021995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com