Reputation: 111
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:
Upvotes: -2
Views: 89
Reputation: 44414
This is a good case for making your own container class, instead of relying directly on a Map:
public class IndexSet {
private final Map<Long, Index> indexes = new HashMap<>();
public boolean contains(long id) {
return indexes.containsKey(id);
}
public Index get(long id) {
return indexes.get(id);
}
public void add(Index index) {
return indexes.put(index.getId(), index);
}
public List<Index> allByDate() {
List<Index> list = new ArrayList<>(indexes.values());
list.sort(Comparator.comparing(Index::getDate));
return list;
}
}
Upvotes: 0