Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map between pairs and values

I need to create a map which will cache results of a third party lookup service. The request is made up of two objects for example, time and month. The map needs to map between (time, month) and a result.

My initial idea is to make an object to wrap time and month into effectively a tuple object, so the cache is a map between this object and the result.

Is there a better way of doing this, without needing to wrap the request into the tuple object each time we need to use the cache?

Many thanks.

like image 669
Mahout Avatar asked Dec 01 '15 16:12

Mahout


1 Answers

My initial idea is to make an object to wrap time and month into effectively a tuple object

That's the right idea. Override hashCode() and equals(Object) of your tuple to make it work with HashMap<TimeMonthTuple>, or compareTo(TimeMonthTuple) to make it work with TreeMap<TimeMonthTuple>

Is there a better way of doing this?

This is the most straightforward way, unless you have a class that can replace TimeMonthTuple with something that makes sense. For example, time and date could be combined into a Date object.

In certain cases you could make a key based on a primitive wrapper. For example, if time is expressed as the number of minutes since midnight and month is a number between 1 and 12, inclusive, you could wrap both values into an Integer, and use it as a key:

Integer makeTimeMonthKey(int time, int month) {
    return (time * 12) + (month - 1);
}
like image 150
Sergey Kalinichenko Avatar answered Sep 24 '22 16:09

Sergey Kalinichenko