Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.junit.Assert;
- public class FunctionalMap {
- public interface Map<K, V> {
- V map(K key);
- }
- public static Map empty() {
- return new Map() {
- @Override
- public Object map(Object key) {
- return null;
- }
- };
- }
- public static <K, V> Map<K, V> add(final Map<K, V> map, final K newKey, final V newValue) {
- return new Map<K, V>() {
- @Override
- public V map(K key) {
- return key.equals(newKey) ? newValue : map.map(key);
- }
- };
- }
- public static <K, V> V find(Map<K, V> map, K key) {
- return map.map(key);
- }
- public static void main(String[] args) {
- Map<String, Integer> emptyMap = empty();
- Map<String, Integer> m1 = add(emptyMap, "x", 1);
- Map<String, Integer> m2 = add(m1, "y", 2);
- Map<String, Integer> m3 = add(m2, "x", 3);
- Assert.assertEquals(new Integer(1), find(m1, "x"));
- Assert.assertEquals(new Integer(1), find(m2, "x"));
- Assert.assertEquals(new Integer(2), find(m2, "y"));
- Assert.assertNull(find(m2, "z"));
- Assert.assertEquals(new Integer(3), find(m3, "x"));
- Assert.assertEquals(new Integer(2), find(m3, "y"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment