[英]Create multiple Array lists by using Hashmap
I have class named Student
and it has String attribute date
. 我有一个名为Student
类,它有String属性date
。 I have list of all my Students and now I want to create multiple ArrayLists
which are grouped by their dates
. 我有我所有学生的列表,现在我想创建多个按dates
分组的ArrayLists
。
I want to use hashmap: 我想使用hashmap:
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? 如何创建多个学生的ArrayLists,按其属性的String值分组?
The easiest way it to use Java 8 Streams : 使用Java 8 Streams的最简单方法:
Map<String, List<Student>> map =
students.stream()
.collect(Collectors.groupingBy(Student::getDate));
Where getDate
is the method of Student
class by which you wish to group the Student
s. 凡getDate
是方法Student
类的,你想组的Student
秒。
To complete the answer for pre-Java 8 code: 要完成Java 8之前的代码的答案:
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);
}
Try this: 尝试这个:
Map<String, List<Student>> map= new HashMap<String, List<Student>();
List<Student> list;
for (Student student: students) {
list = map.get(student.getDate());
if (list == null) {
list = new ArrayList<Student>();
map.put(student.getDate(), list);
}
list.add(student);
}
The idea is to check if the date already exists in the map. 我们的想法是检查地图中是否已存在日期。 If it exists add the student to the corresponding list. 如果存在,请将学生添加到相应的列表中。 If it does not, add a new list with the student as the 1st record in the new list. 如果没有,请添加一个新列表,将该学生作为新列表中的第一条记录。
Here is what works. 这是有效的。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = getStudents();
Map<String, ArrayList<Student>> map = new HashMap<String, ArrayList<Student>>();
for (Student i : students) {
if (map.containsKey(i.getDate())) {
map.get(i.getDate()).add(i);
} else {
ArrayList<Student> newList = new ArrayList<Student>();
newList.add(i);
map.put(i.getDate(), newList);
}
}
System.out.println(map);
}
private static ArrayList<Student> getStudents() {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("Hari", "12/05/2015"));
list.add(new Student("Zxc", "14/05/2015"));
list.add(new Student("Bob", "12/05/2015"));
list.add(new Student("Ram", "14/05/2015"));
return list;
}
}
class Student {
public Student(String name, String date) {
this.name = name;
this.date = date;
}
private String name;
private String date;
public String getDate() {
return date;
}
@Override
public String toString() {
return name;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.