Skip to content

Instantly share code, notes, and snippets.

@naosim
Created June 2, 2017 20:30
Show Gist options
  • Save naosim/fc03920f01ceab1598d369e9cfb614c3 to your computer and use it in GitHub Desktop.
Save naosim/fc03920f01ceab1598d369e9cfb614c3 to your computer and use it in GitHub Desktop.
InMemoryTable
// package
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
public class InMemoryTable<K, V> {
private final Map<K, List<Record<K, V>>> map = new HashMap<>();
private final Supplier<LocalDateTime> localDateTimeSupplier;
private long id = 1;
public InMemoryTable(Supplier<LocalDateTime> localDateTimeSupplier) {
this.localDateTimeSupplier = localDateTimeSupplier;
}
public InMemoryTable() {
this.localDateTimeSupplier = LocalDateTime::now;
}
private long createId() {
return id++;
}
public List<Record<K, V>> find(K key) {
if(!map.containsKey(key)) {
return new ArrayList<>();
}
return map.get(key);
}
public Optional<Record<K, V>> findById(String id) {
return map.values()
.stream()
.map(l -> l.stream().filter(v -> v.getId().equals(id)).findFirst())
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
}
public Optional<Record<K, V>> findLast(K key) {
List<Record<K, V>> l = find(key);
return l.isEmpty() ? Optional.empty() : Optional.of(l.get(l.size() - 1));
}
public String insert(Function<Long, String> idFactory, RecordContainer<K, V> recordContainer) {
if(!map.containsKey(recordContainer.getKey())) {
map.put(recordContainer.getKey(), new ArrayList<>());
}
String id = idFactory.apply(createId());
map.get(recordContainer.getKey()).add(new Record<K, V>(recordContainer, id, localDateTimeSupplier.get()));
return id;
}
public String insert(RecordContainer<K, V> recordContainer) {
return insert((v) -> "" + v, recordContainer);
}
public static class RecordContainer<K, V> {
private final K key;
private final V value;
public RecordContainer(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public static class Record<K, V> extends RecordContainer<K, V> {
private final String id;
private final LocalDateTime eventDateTime;
public Record(K key, V value, String id, LocalDateTime eventDateTime) {
super(key, value);
this.id = id;
this.eventDateTime = eventDateTime;
}
public Record(RecordContainer<K, V> recordContainer, String id, LocalDateTime eventDateTime) {
super(recordContainer.getKey(), recordContainer.getValue());
this.id = id;
this.eventDateTime = eventDateTime;
}
public String getId() {
return id;
}
public LocalDateTime getEventDateTime() {
return eventDateTime;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment