Created
January 29, 2014 10:16
-
-
Save ybonnel/8685105 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Optional; | |
import java.util.TreeMap; | |
import java.util.function.BinaryOperator; | |
public class TemporelMap<K extends Comparable<K>, V> { | |
private TreeMap<K, V> treeMap = new TreeMap<>(); | |
private BinaryOperator<V> add; | |
public TemporelMap(BinaryOperator<V> add) { | |
this.add = add; | |
} | |
public Optional<V> get(K key) { | |
return treeMap.headMap(key, true).values().stream().reduce(add); | |
} | |
public void add(K key, V value) { | |
treeMap.put(key, value); | |
} | |
@Override | |
public String toString() { | |
return treeMap.toString(); | |
} | |
public static void main(String[] args) { | |
TemporelMap<Integer, Integer> map = new TemporelMap<>((n1, n2) -> n1 + n2); | |
System.out.println(map.toString()); | |
map.add(1, 2); | |
map.add(3, 4); | |
map.add(4, 7); | |
map.add(5, 6); | |
System.out.println(map.toString()); | |
System.out.println("Value for 2 = " + map.get(2)); | |
System.out.println("Value for 4 = " + map.get(4)); | |
System.out.println("Value for 7 = " + map.get(7)); | |
map.add(2, 3); | |
System.out.println(map.toString()); | |
System.out.println("Value for 2 = " + map.get(2)); | |
System.out.println("Value for 4 = " + map.get(4)); | |
System.out.println("Value for 7 = " + map.get(7)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment