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

com.jnape.palatable.lambda.functions.builtin.fn2.ToMap Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.functions.builtin.fn2;

import com.jnape.palatable.lambda.functions.Fn0;
import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.Fn2;

import java.util.Map;

import static com.jnape.palatable.lambda.functions.builtin.fn3.FoldLeft.foldLeft;

/**
 * Given an {@link Fn0} of some {@link Map} M, create an instance of M and put all of the
 * entries in the provided Iterable into the instance. Note that instances of M must support
 * {@link java.util.Map#put} (which is to say, must not throw on invocation).
 *
 * @param  the key element type
 * @param  the value element type
 * @param  the resulting map type
 */
public final class ToMap> implements Fn2, Iterable>, M> {

    private static final ToMap INSTANCE = new ToMap<>();

    private ToMap() {
    }

    @Override
    public M checkedApply(Fn0 mFn0, Iterable> entries) {
        return foldLeft((m, kv) -> {
            m.put(kv.getKey(), kv.getValue());
            return m;
        }, mFn0.apply(), entries);
    }

    @SuppressWarnings("unchecked")
    public static > ToMap toMap() {
        return (ToMap) INSTANCE;
    }

    public static > Fn1>, M> toMap(Fn0 mFn0) {
        return ToMap.toMap().apply(mFn0);
    }

    public static > M toMap(Fn0 mFn0,
                                                      Iterable> entries) {
        return toMap(mFn0).apply(entries);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy