I have a specific problem. I need to create a map of objects identified by a custom Index class consisting of two fields: Long id and Date date. Is it possible to make TreeMap sorted by the date field, but have .containsKey check the id field?
public class Index implements Comparable<Index> {
public Long id;
public Date date;
public Index(Long id, Date date) {
this.id = id;
this. Date = date;
}
@Override
public int compareTo(Index i) {
return date.compareTo(i.date);
}
@Override
public Boolean equals(Object o) {
if (o instanceof Index) {
Index i = (Index) o;
return id.equals(i.id);
}
return false;
}
}
And code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Map<Index,Object> items = new TreeMap<>();
items.put(new Index(10L, formatter.parse("2023-03-14 10:00")), 10L);
items.put(new Index(20L, formatter.parse("2023-03-14 08:00")), 20L);
And what I want to achieve is:
- items.containsKey(10L) should check if there is an Index object with id == 10L.
- items.put should work normally, so that Index objects can be added normally.
- items should be sorted by the date field in the Index object, so the 20L will be the first item, and 10L will be the second item.
This is a good case for making your own container class, instead of relying directly on a Map: