1+ package com .rampatra .misc ;
2+
3+ import java .util .Date ;
4+ import java .util .HashMap ;
5+ import java .util .Map ;
6+
7+ /**
8+ * @author rampatra
9+ * @since 2019-05-15
10+ */
11+ public class MapWithTimestamp <K , V > {
12+
13+ private final Map <K , Map <Long , V >> map = new HashMap <>();
14+
15+ public V get (K key , Long timestamp ) {
16+ Map <Long , V > entry = map .get (key );
17+
18+ return entry != null ? entry .get (timestamp ) : null ;
19+ }
20+
21+ public void put (K key , Long timestamp , V value ) {
22+ Map <Long , V > entry = map .get (key );
23+
24+ if (entry == null ) {
25+ map .put (key , new HashMap <Long , V >() {{
26+ put (timestamp , value );
27+ }});
28+ } else {
29+ entry .put (timestamp , value );
30+ }
31+ }
32+
33+ public static void main (String [] args ) throws Exception {
34+ MapWithTimestamp <Integer , Integer > mapWithTimestamp = new MapWithTimestamp <>();
35+ long timestamp1 ;
36+ long timestamp2 ;
37+ long timestamp3 ;
38+
39+ mapWithTimestamp .put (1 , timestamp1 = new Date ().getTime (), 10_0 );
40+ mapWithTimestamp .put (2 , timestamp2 = new Date ().getTime (), 20_0 );
41+ Thread .sleep (100 );
42+ mapWithTimestamp .put (2 , new Date ().getTime (), 20_1 );
43+ Thread .sleep (100 );
44+ mapWithTimestamp .put (2 , new Date ().getTime (), 20_2 );
45+ mapWithTimestamp .put (3 , timestamp3 = new Date ().getTime (), 30_0 );
46+ System .out .println (mapWithTimestamp .get (2 , timestamp2 ));
47+ System .out .println (mapWithTimestamp .get (3 , timestamp2 ));
48+ System .out .println (mapWithTimestamp .get (3 , timestamp3 ));
49+ }
50+ }
0 commit comments