作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我用谷歌搜索过,但没有遇到转换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/
我是一名优秀的程序员,十分优秀!