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