使用 Hashmap 创建多个数组列表 [英] Create multiple Array lists by using Hashmap
本文介绍了使用 Hashmap 创建多个数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 Student
的类,它有 String 属性 date
.我有我所有学生的列表,现在我想创建多个 ArrayLists
,它们按他们的 dates
分组.
I have class named Student
and it has String attribute date
. I have list of all my Students and now I want to create multiple ArrayLists
which are grouped by their dates
.
我想使用哈希图:
ArrayList students = getStudents();
Map map<String, ArrayList<Student>> = new HashMap<String, ArrayList<Student>);
for (Student i: students) {
// There must be something
}
如何创建多个按学生属性的字符串值分组的学生数组列表?
How I can create multiple ArrayLists of Students which are grouped by their String value of their attribute?
推荐答案
使用 Java 8 Streams 的最简单方法:
The easiest way it to use Java 8 Streams :
Map<String, List<Student>> map =
students.stream()
.collect(Collectors.groupingBy(Student::getDate));
其中 getDate
是 Student
类的方法,您希望通过该方法对 Student
进行分组.
Where getDate
is the method of Student
class by which you wish to group the Student
s.
要完成 Java 8 之前代码的答案:
To complete the answer for pre-Java 8 code:
Map<String, List<Student>> map = new HashMap<>();
for (Student s : students) {
List<Student> list = map.get(s.getDate());
if (list == null) {
list = new ArrayList<Student>();
map.put (s.getDate(), list);
}
list.add (s);
}
这篇关于使用 Hashmap 创建多个数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文