Create multiple lists of arrays using Hashmap
I have a class named Student
and it has a String attribute date
. I have a list of all my students and now I want to create several ArrayLists
that are grouped by them dates
.
I want to use hashmap:
ArrayList students = getStudents();
Map map<String, ArrayList<Student>> = new HashMap<String, ArrayList<Student>);
for (Student i: students) {
// There must be something
}
How can I create multiple ArrayLists of students that are grouped by their string values ββof their attribute?
source to share
Easiest way to use Java 8 streams:
Map<String, List<Student>> map =
students.stream()
.collect(Collectors.groupingBy(Student::getDate));
Where getDate
is the class method Student
by which you want to group Student
s.
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);
}
source to share
Try the following:
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);
}
source to share
The idea is to check if the date exists on the card. If it exists, add the student to the appropriate list. If not, add a new list with the student as the first entry in the new list.
Here's 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;
}
}
source to share