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