All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.nginate.commons.lang.function.memoize.FunctionMemoizer Maven / Gradle / Ivy

The newest version!
/**
 * Copyright © 2016
 * Maksim Lozbin 
 * Oleksii Ihnachuk 
 *
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.github.nginate.commons.lang.function.memoize;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * Intermediate operation for any functional flow to cache function results. As example let's assume you have a function
 * that is downloading some file from remote instance, reads first 666 lines and converts them to some dto. Using this
 * wrapper, you can save the results of 'heavy' function and reuse them.
 *
 * @param  input type
 * @param  result type
 * @since 1.0
 */
public class FunctionMemoizer {
    /**
     * Local cache for functions' results
     */
    private final Map cache = new ConcurrentHashMap<>();

    /**
     * Try to get already preloaded results of provided function, or compute and save in cache.
     *
     * @param function function to compute something from input
     * @return compute result (from cache if present)
     * @see Map#computeIfAbsent(Object, Function)
     */
    public Function doMemoize(Function function) {
        return input -> cache.computeIfAbsent(input, function);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy