天天看點

一個使用Java Map.computeIfAbsents實作非波拉契(fibonacci)數列的列子

package fibonacci;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class FibonacciTest {
    
    static Map<Integer, Integer> cache = new HashMap<>();
    static int fibonacci(int i) {
        if (i == 0)
            return i;
     
        if (i == 1)
            return 1;
     
        /*If the specified key is not already associated with a value (or is mapped to null),           attempts to compute its 
         * value using the given mapping function and enters it into this map unless null.
        */
        Function<? super Integer, ? extends Integer> mapper =  (key) -> {
            System.out.println(
                    "Using Java 8 Slow calculation of " + key);
         
                return fibonacci(i - 2) + fibonacci(i - 1);
            };
            
        return cache.computeIfAbsent(i, mapper);
    }
    
    static int fibonacciJava7(int i) {
        if (i == 0)
            return i;
     
        if (i == 1)
            return 1;
     
        Integer result = cache.get(i);
        if (result == null) {
            synchronized (cache) {
                result = cache.get(i);
     
                if (result == null) {
                    System.out.println(
                        "Slow calculation of " + i);
     
                    result = fibonacci(i - 2) 
                           + fibonacci(i - 1);
                    cache.put(i, result);
                }
            }
        }
     
        return result;
    }
    
    public static void main(String[] args) {
        /*for (int i = 0; i < 10; i++)
            System.out.println(
                "f(" + i + ") = " + fibonacciJava7(i));*/
        for (int i = 0; i < 10; i++)
            System.out.println(
                "f(" + i + ") = " + fibonacci(i));
    }
}