Nolias
Nolias

Reputation: 111

Java TreeMap with custom class (Long, Date) as Key to sort by Date, but put/get by Long

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:

  1. items.containsKey(10L) should check if there is an Index object with id == 10L.
  2. items.put should work normally, so that Index objects can be added normally.
  3. 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.

Upvotes: -2

Views: 89

Answers (1)

VGR
VGR

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

Related Questions