Bohtvaroh

Map on Closures in Java

Aug 4th, 2011
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.30 KB | None | 0 0
  1. import org.junit.Assert;
  2.  
  3. public class FunctionalMap {
  4.  
  5.     public interface Map<K, V> {
  6.         V map(K key);
  7.     }
  8.  
  9.     public static Map empty() {
  10.         return new Map() {
  11.             @Override
  12.             public Object map(Object key) {
  13.                 return null;
  14.             }
  15.         };
  16.     }
  17.  
  18.     public static <K, V> Map<K, V> add(final Map<K, V> map, final K newKey, final V newValue) {
  19.         return new Map<K, V>() {
  20.             @Override
  21.             public V map(K key) {
  22.                 return key.equals(newKey) ? newValue : map.map(key);
  23.             }
  24.         };
  25.     }
  26.  
  27.     public static <K, V> V find(Map<K, V> map, K key) {
  28.         return map.map(key);
  29.     }
  30.  
  31.     public static void main(String[] args) {
  32.         Map<String, Integer> emptyMap = empty();
  33.  
  34.         Map<String, Integer> m1 = add(emptyMap, "x", 1);
  35.         Map<String, Integer> m2 = add(m1, "y", 2);
  36.         Map<String, Integer> m3 = add(m2, "x", 3);
  37.  
  38.         Assert.assertEquals(new Integer(1), find(m1, "x"));
  39.  
  40.         Assert.assertEquals(new Integer(1), find(m2, "x"));
  41.         Assert.assertEquals(new Integer(2), find(m2, "y"));
  42.         Assert.assertNull(find(m2, "z"));
  43.  
  44.         Assert.assertEquals(new Integer(3), find(m3, "x"));
  45.         Assert.assertEquals(new Integer(2), find(m3, "y"));
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment