Use a TreeMap
instead of HashMap
, which automatically sorts according to the key's natural order.
To sort the ArrayList
, use the static Collections#sort(List, Comparator)
method, specifying a comparator to sort the Events
objects in the list. For example, assuming you want to sort by the first parameter of the Events
constructor called id
, then you would call sort
as follows:
Map<String, List<Events>> h = new HashMap<>();
List<Events> a = new ArrayList<>();
a.add(new Events("1", "name1", "Address1"));
a.add(new Events("2", "name2", "Address2"));
Collections.sort(a, new Comparator<Events>() {
@Override
public int compare(Events o1, Events o2) {
return o1.getId().compareTo(o2.getId());
}
});
h.put("10-12-2014", a);
... // similarly for list a1
Collections.sort(a1, new Comparator<Events>() {
@Override
public int compare(Events o1, Events o2) {
return o1.getId().compareTo(o2.getId());
}
});
h.put("08-11-2014", a1);
Note that it is better to declare the list and map variables to the interfaces, not the implementation, i.e. h
is declared of type Map
instead of HashMap
, and a
of type List
.
Alternatively, consider putting the Events
elements in a TreeSet
instead of an ArrayList
, and have the Events
class implements the Comparable
interface:
class Events implements Comparable<Events> {
private String id;
...
@Override
public int compareTo(Events o) {
return this.getId().compareTo(o.getId());
}
}